“ref”关键字和引用类型
我的团队中的某个人偶然发现了引用类型上ref关键字的特殊用法
class A { /* ... */ } class B { public void DoSomething(ref A myObject) { // ... } }
是否有人理智会做这样的事情? 我在C#中找不到这个用途
让
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
仅当他们想要将作为myObject
传入的对象的引用更改为其他对象时。
public void DoSomething(ref A myObject) { myObject = new A(); // The object in the calling function is now the new one }
这可能不是他们想做的事情,也不需要ref
。
如果该方法应该更改传递给方法的变量中存储的引用,则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
这没什么特别的。 如果要从方法返回多个值,或者只是不想将返回值重新分配给作为参数传递的对象,则引用变量。
像这样:
int bar = 4; foo(ref bar);
代替:
int bar = 4; bar = foo(bar);
或者,如果要检索多个值:
int bar = 0; string foobar = ""; foo(ref bar, ref foobar);