考虑以下代码:
public class Program
{
private static void Main(string[] args)
{
var person1 = new Person { Name = "Test" };
Console.WriteLine(person1.Name);
Person person2 = person1;
person2.Name = "Shahrooz";
Console.WriteLine(person1.Name); //Output: Shahrooz
person2 = null;
Console.WriteLine(person1.Name); //Output: Shahrooz
}
}
public class Person
{
public string Name { get; set; }
}
显然,当分配person1
给person2
且Name
属性person2
更改时,Name
ofperson1
也将更改。person1
并person2
具有相同的参考。
为什么在时person2 = null
,person1
变量也不会为null?