【发布时间】:2011-02-28 03:46:09
【问题描述】:
我试图了解如何通过“引用”分配给 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 参数”分配给字段会丢失引用。
在分配给字段时有什么方法可以保留引用?
谢谢。
【问题讨论】:
标签: c# reference parameters field