不是程序员,我想了解以下代码:
A a=new A();
B a=new B();
a=b;
c=null;
b=c;
如果变量只包含引用,那么'a'到底是否为空?
答案 0 :(得分: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
输出将是:
{{1}}
答案 1 :(得分: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”最终不是空的。