C# 类 引用类型

C# Classes reference types

我对引用类型的实际工作方式有疑问。 我有一个 class 人,有两个属性名称和年龄。我正在创建一个 Person class (objPerson1) 的对象,为这两个属性分配一些值并将该对象分配给另一个 Person 类型的对象 (objPerson2)。现在的问题是在我更改 Name 和 Age 属性 并打印它们时分配后,对象共享相同的 Name 和 Age 这很好,因为当我将 null 值分配给对象本身时它们是引用 type.But 然后其他对象没有得到 nullified.Below 是代码

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public static void Main(string[] args)
{
    Person objPerson1 = new Person();
    objPerson1.Name = "Tom";
    objPerson1.Age = 10;

    Person objPerson2 = objPerson1;
    objPerson2.Name = "Jerry";
    objPerson2.Age = 15;
    Console.WriteLine($" Person1-{objPerson1.Name},{objPerson1.Age} and Person2-{objPerson2.Name},{objPerson2.Age}");
    //Above line prints   Person1-Jerry,15 and Person2-Jerry,15
    //which is right as both are sharing same address.But when I wrote following code it confused me alot.
}

public static void Main(string[] args)
{
    Person objPerson1 = new Person();
    objPerson1.Name = "Tom";
    objPerson1.Age = 10;
    Person objPerson2 = objPerson1;
    objPerson2 = null;
    //After executing above line objPerson2 was null but objPerson1 were still having the values for Name and Age.
}

因为它们是引用类型,并且如果我将 null 分配给 objPerson2,它们都指向相同的地址,objPerson1 也应该是 null,如果我错了,副versa.Correct我

objPerson2只是指向objPerson1初始化分配的内存的指针。将 null 分配给 objPerson2 会删除此指针。 objPerson1 仍然指向那个内存,因此它保持它的价值并且不会成为 null 一旦 objPerson1 成为。

有点简化,但希望足以让您理解:

Person objPerson1 = new Person();

堆:为对象分配的内存

堆栈:objPerson1 = 堆对象的地址

objPerson1.Name = "Tom";
objPerson1.Age = 10;

堆:正在用值填充。

堆栈:未改变(仍然是相同的地址)

Person objPerson2 = objPerson1;

堆栈:另一个变量获得相同的地址

堆:不变

objPerson2 = null;

堆栈:变量objPerson2得到值0x00000000

注意objPerson1还有堆的地址,堆上的对象仍然存在。所以objPerson1还是"works".