为什么内部实例变为空

本文关键字:实例 内部 为什么 | 更新日期: 2023-09-27 18:04:12

我想弄清楚为什么赋值器(myC.myself)在编译行后变为空?提前谢谢。

namespace AequalsBequalsC
{
  class Program
  {
    static void Main(string[] args)
    {
        A myA = new A();
        A myB = new A();
        myB.a = 8;
        A myC = new A();
        myC.a = 9;
        myC.myself = myA;
        myC = myC.myself;
        Console.WriteLine("myA.a is {0}, myB.a is {1}, myC.a is {2}", myA.a,myB.a, myC.a);
        Console.ReadLine();
    }
  }
  public class A
  {
    public int a = 4;
    public A myself;
  }
}

为什么内部实例变为空

永远不会变成null总是null。当您创建类A的新实例时,我自己从未分配variable,因此是null

当您将myA值赋给myC.myself,然后将相同的myA值赋给myC时,myC不再是您创建的第三个对象,而是第一个对象,它从一开始就没有设置myself

现在,如果你做了这样的事情(我强烈不建议!),它不会是空的:

    class Program
    {
        static void Main(string[] args)
        {
            A myA = new A();
            A myB = new A();
            myB.a = 8;
            A myC = new A();
            myC.a = 9;
            myC.myself = myA;
            myC = myC.myself;
            Console.WriteLine("myA.a is {0}, myB.a is {1}, myC.a is {2}", myA.a, myB.a, myC.a);
            Console.ReadLine();
        }
    }
    public class A
    {
        public int a = 4;
        public A myself;
        public A()
        {
            this.myself = this;
        }
    }