C#引用变量使用澄清

本文关键字:引用 变量 | 更新日期: 2024-10-22 21:53:12

由于不是程序员,我想了解以下代码:

A a=new A();
B a=new B();
a=b;      
c=null;
b=c; 

如果变量只包含引用,那么"a"最终会为null吗?

C#引用变量使用澄清

假设所有对象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

你需要在脑海中脱离两个概念;引用对象引用本质上是托管堆上对象的地址。因此:

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"最终不为空。