C#多态:获取派生类'财产而不是基类'同名字段

时间:2014-04-13 01:26:03

标签: c# properties polymorphism field derived

我有一个基类Ref<>:

public class Ref<T>
    {
        public T Value;

        public Ref() { }

        public Ref(T initialValue)
        {
            Value = initialValue;
        }
    }

和派生类RefProperty&lt;&gt;:

public class RefProperty<T> : Ref<T>
    {
        public Func<T> Getter;
        public Action<T> Setter;

        public T Value
        {
            get { return Getter(); }
            set { Setter(value); }
        }

        public RefProperty(Func<T> getter, Action<T> setter)
        {
            Getter = getter;
            Setter = setter;
        }
    }

然后我声明一个Ref并将其初始化为RefProperty(多态):

Ref<int> IntDoubled = new RefProperty<int>(getIntDoubled, setIntDoubled);

其中getIntDoubled和setIntDoubled是预期的方法:

private int getIntDoubled()
        { return myInt * 2; }
private void setIntDoubled(int value)
        { myInt = value / 2; } 

并且myInt是声明的测试整数:

int myInt = 10;

然后打印:

Console.WriteLine(IntDoubled.Value);

我希望它会返回20,因为派生类IntDoubled中名为Value的属性调用了返回myInt * 2的getIntDoubled()方法。 但是由于IntDoubled被声明为Ref而不是RefProperty,它返回基类的Value字段(由于未设置值,因此返回0)。

所以问题是:我怎样才能得到派生类&#39;属性而不是基类&#39;如果实例是多态的,那么同名的字段?

1 个答案:

答案 0 :(得分:4)

您的基类和子类之间的一致性如何? You shouldn't be exposing fields publicly无论如何,因此在基类中创建Value作为auto-prop是很有意义的。现在,您可以将其设置为虚拟并轻松覆盖它。任何领域/财产混乱都会完全消除。

public class Ref<T>
{
    public virtual T Value{get;set;}

    public Ref() { }

    public Ref(T initialValue)
    {
        Value = initialValue;
    }
}



public class RefProperty<T> : Ref<T>
{
    public Func<T> Getter;
    public Action<T> Setter;

    public override T Value
    {
        get { return Getter(); }
        set { Setter(value); }
    }

    public RefProperty(Func<T> getter, Action<T> setter)
    {
        Getter = getter;
        Setter = setter;
    }
}