我的团队中有人偶然发现了在引用类型上使用 ref 关键字的一种奇特用法。
class A { /* ... */ }
class B
{
public void DoSomething(ref A myObject)
{
// ...
}
}
有理智的人为什么要这样做?我在C#中找不到用处。
我的团队中有人偶然发现了在引用类型上使用 ref 关键字的一种奇特用法。
class A { /* ... */ }
class B
{
public void DoSomething(ref A myObject)
{
// ...
}
}
有理智的人为什么要这样做?我在C#中找不到用处。
只有当他们想要将对作为 myObject
传递的对象的 引用 更改为另一个对象时才需要这样做。
public void DoSomething(ref A myObject)
{
myObject = new A(); // The object in the calling function is now the new one
}
很有可能这不是他们想要做的,而且ref
并不是必需的。
让
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
这没什么特别的。如果你想从一个方法返回多个值,或者不想重新分配返回值给作为参数传入的对象,那么你可以引用变量。
像这样:
int bar = 4;
foo(ref bar);
改为:
int bar = 4;
bar = foo(bar);
或者如果你想要检索多个值:
int bar = 0;
string foobar = "";
foo(ref bar, ref foobar);
int
。 - abatishchevref
关键字在方法需要更改传递给方法的变量中存储的引用时非常有用。如果不使用 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