2012-08-07 62 views
1

作爲不是一個程序員,我想明白下面的代碼:C#參考變量使用澄清

A a=new A(); 
B a=new B(); 

a=b;  
c=null; 

b=c; 

如果這些變量都抱着僅供參考,將「A」進行到底空?

+0

不,變量'a'的值不會被改變。賦值給引用類型的變量會創建引用的副本,但不會引用該引用的對象。 – adatapost 2012-08-07 06:58:56

+1

你被重新聲明'a',你永遠不會聲明'b'和'c',你的類型不匹配。請發佈正確的代碼,否則我們無法回答你的問題。 – 2012-08-07 07:00:04

回答

5

您需要離婚在你的心中兩個概念; 參考對象參考本質上是託管堆上的對象的地址。所以:

A a = new A(); // new object A created, reference a assigned that address 
B b = new B(); // new object B created, reference b assigned that address 
a = b; // we'll assume that is legal; the value of "b", i.e. the address of B 
     // from the previous step, is assigned to a 
c = null; // c is now a null reference 
b = c; // b is now a null reference 

這不會影響「a」或「A」。 「a」仍然包含我們創建的B的地址。

所以不,「a」最後不是零。

6

假設所有對象a,b,c來自同一類,a將不會是null。在分配到c之前,它將保留參考值b的值。

假設您有以下類

class Test 
{ 
    public int Value { get; set; } 
} 

然後嘗試:

Test a = new Test(); 
a.Value = 10; 
Test b = new Test(); 
b.Value = 20; 
Console.WriteLine("Value of a before assignment: " + a.Value); 
a = b; 
Console.WriteLine("Value of a after assignment: " + a.Value); 
Test c = null; 
b = c; 
Console.WriteLine("Value of a after doing (b = c) :" + a.Value); 

輸出將是:

Value of a before assignment: 10 
Value of a after assignment: 20 
Value of a after doing (b = c) :20