2012-08-07 106 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