引用类型与值类型 [英] Reference type vs value type

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

问题描述

我正在阅读有关C#中的结构和类的信息,据我了解,结构是值类型,而类是引用类型.但是对于类对象作为参数传递给方法时的行为,我有些困惑.

I'm reading about structs and classes in C# and to my understanding structs are value types and classes are reference types. But I'm a little confused about how class objects behave when they are passed as parameters to a method.

假设我有以下代码:

public class Program
{
    public static void Main(string[] args)
    {
        var program = new Program();
        var person = new Person
        {
            Firstname = "Bob",
        };

        Console.WriteLine(person.Firstname);
        program.ChangeName(person);
        Console.WriteLine(person.Firstname);
        program.Kill(person);
        Console.WriteLine(person.Firstname);
        Console.Read();
    }

    public void ChangeName(Person p)
    {
        p.Firstname = "Alice";
    }

    public void Kill(Person p)
    {
        p = null;
    }
}

当我将Person类的实例传递给Program.ChangeName()并将person.Firstname的值更改为Alice时,更改将反映在原始人对象上,如我的Program.Main()中所实例化的那样我希望p参数是对person的引用.但是,当我尝试将p设置为null时,似乎没有变化.为什么会这样?

When I pass my instance of the Person class to Program.ChangeName() and change the value of person.Firstname to Alice, the change is reflected on the original person object as instantiated in my Program.Main() which is what I would expect, the p parameter is a reference to person. However, when I attempt to set p to null, there appears to be no change. Why is this?

推荐答案

当您通过引用传递"时,您实际上是在传递引用的副本,因此将引用设置为指向另一个对象(或为null)不会影响原始参考.但是,如果通过取消引用指针的副本来更改对象的属性,则调用者将看到这些更改.

When you "pass by reference" you are really passing a copy of the reference, so setting that reference to point to another object (or null) won't affect the original reference. However if you change properties on the object by dereferencing your copy of the pointer, those changes will be seen by the caller.

如果您想真正通过引用传递并使您的kill方法起作用,则可以添加ref关键字:

If you wanted to truly pass by reference and cause your kill method to work, you could add the ref keyword:

public void Kill(ref Person p)
{
    p = null;
}

这篇关于引用类型与值类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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