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 (Updated By
これは、参照パラメーターをクラス フィールドに割り当てると、 参照。参照を維持するための解決策は、ゲッターとセッターを使用することです。
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」の値を取得および設定できるオブジェクトであり、間の参照を維持します。彼ら。 ref ローカルと ref を返すメソッドは CLR でサポートされていますが、C# ではまだ使用できないことに注意してください。
以上がC# で参照パラメーターをクラス フィールドに割り当てると参照が維持されないのはなぜですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。