作为不是程序员,我想了解以下代码:
A a=new A();
B a=new B();
a=b;
c=null;
b=c;
如果变量只持有引用,“a”最终会为空吗?
假设所有对象 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
您需要在脑海中分离两个概念;参考和对象。_ 引用本质上是托管堆上对象的地址。所以:
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”最终不为空。