"参考"关键字和引用类型 [英] "ref" keyword and reference types
本文介绍了"参考"关键字和引用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人在我的团队偶然发现了一个引用类型
someone in my team stumbled upon a peculiar use of the ref keyword on a reference type
class A { /* ... */ }
class B
{
public void DoSomething(ref A myObject)
{
// ...
}
}
是否有任何理由理智的人会做这样的事情?我找不到这样的使用在C#
Is there any reason someone sane would do such a thing? I can't find a use for this in 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
但如果只是
But if just
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
这篇关于"参考"关键字和引用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文