C# - 连接对先前创建的实例的引用?

C# - Connecting reference to previously created instance?

例如,我创建了以下代码:

class Info
    {
        public string Name;
        public int Age;
    }

class Program
{
    static void Main()
    {
        Info APersonsAccount;
        APersonsAccount = new Info();
        
        APersonsAccount.Name = "NameOfPerson";
        APersonsAccount.Age = 23;
        
        Console.WriteLine("Name: {0,-15} Age: {1,-20}", APersonsAccount.Name, APersonsAccount.Age);
        
        APersonsAccount = new Info();
        
        APersonsAccount.Name = "OtherName";
        APersonsAccount.Age = 25;
        
        Console.WriteLine("Name: {0,-15} Age: {1,-20}", APersonsAccount.Name, APersonsAccount.Age);
    }
}

我现在希望 APersonsAccount 引用我创建的类型 Info 的第一个实例。有什么办法可以解决这个问题,还是只创建一个与第一个实例完全相同的新实例?

第二次执行 APersonsAccount = new Info();,您将覆盖存储在 APersonsAccount 中的引用。 如果您仍想引用您创建的第一个 Info 实例,只需将其存储在不同的变量中即可。 例如

Info AccountInfo1 = new Info();
Info AccountInfo2 = new Info();