创建浅拷贝然后混淆新对象(c#)

时间:2017-08-25 17:21:13

标签: c#

我想知道当我们创建一个对象" a"时会发生什么,然后做一个参考" b"然后我们用" a"创建一个新对象,56会发生什么?我怎么理解" a"失去对56的引用,创建了对20的新引用。制作" b"唯一持有人参考56。

class SingleDigit
{
    public int Digit { get; set; }
    public SingleDigit(int b)
    {
        Digit = b;
    }
}

SingleDigit a = new SingleDigit(56); // creat new object with int 56
SingleDigit b = a; // make a reference to a
b.Digit -= 20; // both a and b's digit is subtracted
a = new SingleDigit(20); // What happens here ? Does a lose its reference to 56 ?

2 个答案:

答案 0 :(得分:2)

    //Create a reference location for variable a. Assign it value 56.
    SingleDigit a = new SingleDigit(56); 

    // Create a new object b and give it reference of a's object location. 
    //So, b.Digit is also 56.
    SingleDigit b = a; 

    //Decrement 20 from b.Digit. 
    //It decrements from a.Digit as well since both 
     //refer to same memory object. So, both become 36.
    b.Digit -= 20; // both a and b's digit is subtracted

    // b holds up to original memory location. 
    //A new memory location has a new object created and 
    //its location is provided to variable a. 
    //a.Digit is now 20, and not 36.
    a = new SingleDigit(20); //a loses its reference to 36

答案 1 :(得分:1)

请参阅评论中提到的优秀资源!

这样您就可以直观地看到发生了什么(过于简化的视图)看看下面的图片:

enter image description here

首先,ab都指的是相同的内存位置,它们引用的值是56.

当你减去20时,此特定内存位置的值变为36。

最后当你做

a = new SingleDigit(20); 

a开始指向包含值20

的新内存位置