"ref"关键字和引用类型

6

我的团队中有人偶然发现了在引用类型上使用 ref 关键字的一种奇特用法。

class A { /* ... */ } 

class B
{    
    public void DoSomething(ref A myObject)
    {
       // ...
    }
}

有理智的人为什么要这样做?我在C#中找不到用处。


请参见这个问题 - Dimitri C.
确实,我在搜索时错过了那个问题。很好的发现。 - Luk
4个回答

16

只有当他们想要将对作为 myObject 传递的对象的 引用 更改为另一个对象时才需要这样做。

public void DoSomething(ref A myObject)
{
   myObject = new A(); // The object in the calling function is now the new one 
}

很有可能这不是他们想要做的,而且ref并不是必需的。


13

class A
{
    public string Blah { get; set; }
}

void Do (ref A a)
{
    a = new A { Blah = "Bar" };
}
然后
A a = new A { Blah = "Foo" };
Console.WriteLine(a.Blah); // Foo
Do (ref a);
Console.WriteLine(a.Blah); // Bar
但是如果只是这样。
void Do (A a)
{
    a = new A { Blah = "Bar" };
}

然后

A a = new A { Blah = "Foo" };
Console.WriteLine(a.Blah); // Foo
Do (a);
Console.WriteLine(a.Blah); // Foo

1
即使已经相当清楚,提供一个明确的示例也可以为Oded所说的内容增加可读性。 - Karl Knechtel
非常感谢,这使得它变得清晰明了! - Luk

0

这没什么特别的。如果你想从一个方法返回多个值,或者不想重新分配返回值给作为参数传入的对象,那么你可以引用变量。

像这样:

int bar = 4;
foo(ref bar);

改为:

int bar = 4;
bar = foo(bar);

或者如果你想要检索多个值:

int bar = 0;
string foobar = "";
foo(ref bar, ref foobar);

事实上,OP谈论的是引用类型而不是值类型,例如int - abatishchev
那么你的意思是值类型不使用引用? - peterthegreat
据我所知,不,值类型每次都是完全复制的,也就是按值传递。这就是为什么它们被称为值类型。 - abatishchev
现在我明白你的意思了。我从来没有想过OP使用了一个实际的对象。当我第一次阅读时,我非常疲倦,已经连续24小时以上没睡觉了。 - peterthegreat

0

ref 关键字在方法需要更改传递给方法的变量中存储的引用时非常有用。如果不使用 ref,则无法更改引用,只有更改对象本身才会在方法外部可见。

this.DoSomething(myObject);
// myObject will always point to the same instance here

this.DoSomething(ref myObject);
// myObject could potentially point to a completely new instance here

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接