在C#中引用类型 [英] Reference type in C#

查看:208
本文介绍了在C#中引用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个code:

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 改变时,名称 PERSON1 也将改变。 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 变量不能为空要么?

Why is it that when person2 = null, the person1 variable will not be null either?

推荐答案

两个 PERSON2 引用的,同一个对象。但这些都是不同的参考。所以,当你运行

Both person and person2 are references, to the same object. But these are different references. So when you are running

person2 = null;

正在改变仅供参考 PERSON2 ,剩下参考和相应的对象不变。

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 引用什么(或,严格来说,由于参考不信邪,参照是不同的条件,请参见注释通过符文FS ),而仍然引用现有的对象。

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#中引用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆