1

作为不是程序员,我想了解以下代码:

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

a=b;      
c=null;

b=c; 

如果变量只持有引用,“a”最终会为空吗?

4

2 回答 2

6

假设所有对象 a、b、c 都来自同一个类,a则不会null。它将b在分配给 之前保存引用的值c

假设您有以下课程

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
于 2012-08-07T06:50:28.280 回答
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”最终不为空。

于 2012-08-07T06:57:57.637 回答