[英]C# reference variables use clarification
由于不是程序员,我想了解以下代码:
A a=new A();
B a=new B();
a=b;
c=null;
b=c;
如果变量仅保留引用,则“ a”最后是否为空?
假设所有对象a,b,c来自同一类,则a
不会为null
。 在将引用b
分配给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
您需要将两个概念离婚。 参考和对象 。 引用实际上是托管堆上对象的地址。 所以:
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”最后不为null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.