首页 >后端开发 >C++ >为什么在 C# 中将引用参数分配给类字段不会维护引用?

为什么在 C# 中将引用参数分配给类字段不会维护引用?

DDD
DDD原创
2025-01-05 21:42:39641浏览

Why Doesn't Assigning a Reference Parameter to a Class Field Maintain the Reference in C#?

在 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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn