在 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 (Updated By Y) (Updated By Z)”。
这是因为将引用参数分配给类字段打破参考。为了维护引用,一个解决方案是使用 getter 和 setter:
sealed class Ref<T> { private readonly Func<T> getter; private readonly Action<T> setter; public Ref(Func<T> getter, Action<T> setter) { this.getter = getter; this.setter = setter; } public T Value { get { return getter(); } set { setter(value); } } } Ref<int> x; void M() { int y = 123; x = new Ref<int>(() => y, z => { y = z; }); x.Value = 456; Console.WriteLine(y); // 456 -- setting x.Value changes y. }
在此示例中,'x' 是一个可以获取和设置 'y' 值的对象,维护之间的引用他们。请注意,虽然 CLR 中支持引用局部变量和引用返回方法,但它们在 C# 中尚不可用。
以上是为什么在 C# 中将引用参数分配给类字段不会维护引用?的详细内容。更多信息请关注PHP中文网其他相关文章!