对于这段代码
Person test;
test = (Person)Person.Clone();
我想问的是:
首先类是引用类型的,引用类型在储存值的时候是先创建一个指针然后再储存具体的值,每个类在定义的时候是不占内存空间的只有在实例化的之后才会向内存去要空间,在储存值的时候引用类型将值的指针放在了内存中的栈中,而将实际的值放在了对中,因此才叫引用类型!
http://topic.csdn.net/u/20090226/00/1cc0d81e-8b7f-40bf-bb39-d882270215d6.html1.那么在代码第一句中就没有申请空间,而第二句代码也不是分配空间,只是将Person类进行浅表复制,再将值传递过去,其过程如何?内存如何分配?
2.还有
Person test=new Person();
     Person  test1=new Person();
      test=test1;
和下面这段代码
Person test;
     Person  test1=new Person();
      test=test1;
有和区别?
请各位大神赐教!!!感激不尽!

解决方案 »

  1.   


    前面是内存中有两个 Person 实例; 后面是仅有一个 Person, test 指向 test1.至于问题 1。 不知道你的 Person 是什么东西。。但是如果 Person 没有实例化,而又调用了它的成员方法。。通常会得到一个 Null Exception。
      

  2.   

    2.还有
    Person test=new Person();
      Person test1=new Person();
      test=test1;
    和下面这段代码
    Person test;
      Person test1=new Person();
      test=test1;
    ------------------
    Person test=new Person();
      Person test1=new Person();
    很显然,你这样做会在堆中 分配两块这种类型的内存,然后test=test1;仅仅是吧test1地址给了test问题一 没太看明白你的意思!呵呵
      

  3.   

    new 其实就是分配个内存。
    Person test=new Person();
      Person test1=new Person();
      test=test1;
    和下面这段代码
    Person test;
      Person test1=new Person();
      test=test1;
    这两个的效果一样。就是第一种多了个分配的内存,后来丢弃了而已。
      

  4.   


    按照你的意思是说在栈上储存了两个堆上的地址,但是只用了其中一个。另一个浪费了。另外对于我的第一个问题,我的Person只是一个类,我是那样写的,运行完全正常。
    求解答?
      

  5.   

    呵呵,刚才写错了,对不住各位了。
    Person Person1=new Person()
    Person test;
    test = (Person)Person1.Clone();
    是这样的。
    谢谢!!!
      

  6.   

    你的那个Person类应该是继承自克隆的那个接口的
    下面的那些楼上的已经解释很清楚了
    我只说一下个人对
    Person Person1=new Person()
    Person test;
    test = (Person)Person1.Clone();
    的理解貌似这个算浅度复制吧 结果应该仅仅是 test指向了person1一样的地址,在这个地址中指向实际存储这个对象的地址
      

  7.   

    不要纠缠什么地址,这是.NET不是C/C++...“引用”本身就是一种数据类型,不是指针那么简单,所谓对象实例的托管堆地址只是引用的一部分...声明一个引用类型对象就在栈中创建了一个“引用”,实例化则在托管堆创建了一个实例对象,并将引用指向该实例对象...在.NET中,暂时忘掉指针吧...
      

  8.   

    Person test;
    这个时候仅仅在栈上储存了一个引用,并没有存储test这个对象
    下面那一句也是得到了一个Person对象,相当新建一个Person实例,此时在托管堆上分配内存,并将test的值设置为分配给Person对象的内存地址2、两者的最后结果没啥区别
    但是Person test和Person test=new Person();
    是有区别的,前者这时只是在堆栈中存了一个引用,在托管队上并没有存储,而后者在托管堆上已经分配了内存