问题描述
考虑这个代码:
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
,并且person2
的Name
属性发生变化时,person1
的 >Name 也将被更改.person1
和 person2
具有相同的引用.
Obviously, when assigning person1
to person2
and the Name
property of person2
is changed, the Name
of person1
will also be changed. person1
and person2
have the same reference.
为什么当person2 = null
时,person1
变量也不为null?
Why is it that when person2 = null
, the person1
variable will not be null either?
推荐答案
person
和 person2
都是对同一个对象的引用.但这些是不同的参考.所以当你跑步时
Both person
and person2
are references, to the same object. But these are different references. So when you are running
person2 = null;
你只改变了引用person2
,而保持引用person
和对应的对象不变.
you are changing only reference person2
, leaving reference person
and the corresponding object unchanged.
我想解释这一点的最好方法是使用简化的插图.以下是之前 person2 = null
的情况:
I guess the best way to explain this is with a simplified illustration. Here is how the situation looked like before person2 = null
:
这是空赋值之后的图片:
And here is the picture after the null assignment:
如您所见,在第二张图片中,person2
没有引用任何内容(或 null
,严格来说,因为没有引用任何内容并且引用了 null
是不同的条件,请参阅 Rune FS 的评论),而 person
仍然引用现有的对象.
As you can see, on the second picture person2
references nothing (or null
, strictly speaking, since reference nothing and reference to null
are different conditions, see comment by Rune FS), while person
still references an existing object.
这篇关于C#中的引用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!