为什么在传递对象时使用 'ref' 关键字? [英] Why use the 'ref' keyword when passing an object?

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

问题描述

如果我将对象传递给方法,为什么要使用 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; }
}

输出为Bar",表示对象作为引用传递.

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

推荐答案

如果要更改对象是什么,请传递 ref:

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并没有引用原来的new TestRef,而是引用了一个完全不同的对象.

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

如果您想更改不可变对象的值,这也可能很有用,例如字符串.string 的值一旦创建就无法更改.但是通过使用 ref,您可以创建一个函数来更改另一个具有不同值的字符串.

This may be useful too if you want to change the value of an immutable object, e.g. a string. You cannot 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.

除非需要,否则使用 ref 不是一个好主意.使用 ref 可以让方法自由地更改其他参数,方法的调用者需要进行编码以确保他们能够处理这种可能性.

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 be coded to ensure they handle this possibility.

此外,当参数类型是对象时,对象变量始终充当对对象的引用.这意味着当使用 ref 关键字时,您将获得对引用的引用.这使您可以按照上面给出的示例中的描述进行操作.但是,当参数类型是原始值(例如int)时,如果在方法内分配了这个参数,则在方法返回后,传入的参数的值将改变:

Also, when the parameter type is an object, then object variables always act as references to the object. This means that 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 (e.g. 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;
}

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

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