Luk*_*Luk 6 .net c# ref reference-type pass-by-reference
我的团队中的某个人偶然发现了引用类型上ref关键字的特殊用法
class A { /* ... */ }
class B
{
public void DoSomething(ref A myObject)
{
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
是否有人理智会做这样的事情?我在C#中找不到这个用途
Ode*_*ded 16
只有当他们想要将对象的引用更改为myObject
另一个对象时才会更改.
public void DoSomething(ref A myObject)
{
myObject = new A(); // The object in the calling function is now the new one
}
Run Code Online (Sandbox Code Playgroud)
这可能不是他们想做的事情,也不是他们想要的ref
.
aba*_*hev 13
让
class A
{
public string Blah { get; set; }
}
void Do (ref A a)
{
a = new A { Blah = "Bar" };
}
Run Code Online (Sandbox Code Playgroud)
然后
A a = new A { Blah = "Foo" };
Console.WriteLine(a.Blah); // Foo
Do (ref a);
Console.WriteLine(a.Blah); // Bar
Run Code Online (Sandbox Code Playgroud)
但如果只是
void Do (A a)
{
a = new A { Blah = "Bar" };
}
Run Code Online (Sandbox Code Playgroud)
然后
A a = new A { Blah = "Foo" };
Console.WriteLine(a.Blah); // Foo
Do (a);
Console.WriteLine(a.Blah); // Foo
Run Code Online (Sandbox Code Playgroud)