为什么要传递一个对象时,使用'裁判'的关键字? [英] Why use the 'ref' keyword when passing an object?

查看:161
本文介绍了为什么要传递一个对象时,使用'裁判'的关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我传递一个对象的方法,我为什么要使用ref关键字?这不是默认的行为呢?

If I am passing an object to a method, why should I use the ref keyword? Isn't this the default behaviour anyway?

例如:

class Program
{
    static void Main(string[] args)
    {
        TestRef t = new TestRef();
        t.Something = "Foo";

        DoSomething(t);
        Console.WriteLine(t.Something);
    }

    static public void DoSomething(TestRef t)
    {
        t.Something = "Bar";
    }
}


public class TestRef
{
    public string Something { get; set; }
}

的输出是棒,这意味着该对象传递作为参考。

The output is "Bar" which means that the object was passed as a reference.

推荐答案

如果你想改变的对象是传递一个参考:

Pass a ref if you want to change what the object is:

TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(ref t);

void DoSomething(ref TestRef t)
{
  t = new TestRef();
  t.Something = "Not just a changed t, but a completely different TestRef object";
}

在调用DoSomething的后,T指的不是原来的新TestRef',而是指一个完全不同的对象。

After calling DoSomething, t does not refer to the original 'new TestRef', but refers to a completely different object.

如果你想改变一个不可变对象的值,如字符串,这可能是有用的了。一旦它被创建,即不能改变一个字符串的值,但通过使用一个参考,你可以创建一个改变的字符串为另一个人,有不同的值的功能。

This may be useful too if you want to change the value of an immutable object, eg a string. You can't change the value of a string once it has been created, but by using a ref, you could create a function that changes the string for another one that has a different value.

编辑:正如其他人提及。它是不使用参考,除非它是需要一个好主意。使用裁判给出的方法,自由地改变一些参数一样,该方法的调用者将需要为codeD,以确保他们处理这种可能性。

As other people have mention. It is not a good idea to use ref unless it is needed. Using ref gives the method freedom to change the argument for something else, callers of the method will need to to be coded to ensure they handle this possibility.

也。当参数类型为对象,则对象变量总是作为参考对象。这意味着,当裁判关键字用于你已经有了一个参考基准。这使您可以在上面给出的例子说明做的事情。但是,当参数类型为原始值(例如int),那么如果该参数的方法中分配,即传入的参数的值将在方法返回后改变:

Also. When the parameter type is an object, then object variables always act as references to the object. This means, when the ref keyword is used you've got a reference to a reference. This allows you to do things as described in the example given above. But, when the parameter type is a primitive value (eg int), then if this parameter is assigned to within the method, the value of the argument that was passed in will be changed after the method returns:

int x = 1;
Change(ref x);
Debug.Assert(x == 5);
WillNotChange(x);
Debug.Assert(x == 5); // Note: x doesn't become 10

void Change(ref int x)
{
  x = 5;
}

void WillNotChange(int x)
{
  x = 10;
}

这篇关于为什么要传递一个对象时,使用'裁判'的关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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