2011-01-11 23 views
6

有人在我的团队偶然发现了一个引用类型“裁判”的关键字和引用类型

class A { /* ... */ } 

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

一个奇特的使用ref关键字的你是不是有了什么理由理智会做这样的事?我无法找到C#

+0

参见[这个问题](HTTP:// stackoverflow.com/questions/961717/c-what-is-the-use-of-ref-for-reference-type-variables)。 – 2011-02-09 11:15:32

+0

确实,我在搜索时错过了这个问题。很好地捕获 – Luk 2011-02-09 15:26:43

回答

12

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

+1,这是Oded正在谈论的一个明确例子,即使它已经很清楚。 – 2011-01-11 09:54:12

15

只有当他们想改变参考来传递进来myObject到一个不同的对象这一个用途。

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

可能这不是他们想要做什么,不需要ref

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 
0

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

像这样:

int bar = 4; 
foo(ref bar); 

代替:

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

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

int bar = 0; 
string foobar = ""; 
foo(ref bar, ref foobar); 
相关问题