如何通过“引用”将其分配给c#中的类字段?
我试图了解如何通过“引用”分配给c#中的类字段。
我有以下示例要考虑:
public class X {
public X()
{
string example = "X";
new Y( ref example );
new Z( ref example );
System.Diagnostics.Debug.WriteLine( example );
}
}
public class Y {
public Y( ref string example )
{
example += " (Updated By Y)";
}
}
public class Z {
private string _Example;
public Z( ref string example )
{
this._Example = example;
this._Example += " (Updated By Z)";
}
}
var x = new X();运行上面的代码时,输出是:
X(由Y更新)
并不是:
X(由Y更新)(由Z更新)
正如我所希望的那样。
似乎为字段分配“ref参数”会丢失引用。
在分配字段时有没有办法保持引用?
谢谢。
30秒到达战场
相关分类