2017-08-25 92 views
-1

我想知道當我們創建一個對象「a」時,會發生什麼,然後創建一個引用「b」,然後我們創建一個新的對象「a 「,56會發生什麼?我該如何理解,「一個」失去其參考56創建一個新的參考20.使「b」的參考的唯一持有人56.創建一個淺拷貝,然後創建一個新對象confused(c#)

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 ? 
+0

所以,你的主要問題是,爲什麼B現在是36和20是一種新的存儲位置? – z3nth10n

+1

運行此代碼後,'a.Digit'爲'20','b.Digit'爲'36','a'和'b'指向單獨的'SingleDigit'實例。如果您對此感到困惑,我建議您只是在LINQPad上試用它們。 –

+0

你可以在這裏看到這個:http://rextester.com/PAFTC79188 – z3nth10n

回答

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

請參見注釋中提到的優秀資源!

所以,你可以想像發生了什麼(一個過度簡化的觀點偏離航線)看看下面的圖片:

enter image description here

起初,雙方ab是指同一個內存位置和價值,他們指是56

當你減去20在這個特別的內存位置值變爲36

最後,當你做

a = new SingleDigit(20); 

a開始指向包含價值20

+0

在這種情況下,無論是淺層還是深層都無法複製。分配引用不應該被稱爲複製,以防止混淆。 –

+0

正如我所說,這是一個過於簡單的描述,以視覺上支持不良貸款!我會改進語言:) – Winnie