我可以覆盖子类中的类变量并将其类型更改为子类

时间:2013-02-14 08:55:05

标签: c# inheritance

是否有一种方法可以覆盖子类中的变量,但也可以将类型更改为该类型的子类。 即

public class BaseClass
{
    public BaseClass() { }
    protected virtual MyBase WorkField { get { return new MyBase(); } }
    public int WorkProperty
    {
        get { return WorkField.Value; }
    }
}

public class DerivedClass : BaseClass
{
    public DerivedClass():base() { }

    /* I get an error here saying that WorkField needs to be MyBase type*/
    protected override MyExtend WorkField 
    { 
        get 
        { 
            return new MyExtend(); 
        }
    }

    //public new int WorkProperty
    //{
    //    get { return 0; }
    //}
}

public class MyBase
{
    public int Value = 1;
}

public class MyExtend : MyBase
{
    public int value = 20;
}

有没有办法做到这一点,但有效吗? 所以我可以有一个在MyBase上执行任务的superClass,然后有一个子类在MyEntend版本上执行任务。 每当我使用它时都不会抛出它。

3 个答案:

答案 0 :(得分:1)

在这种情况下没有理由更改签名。只需返回派生类型:

public class DerivedClass : BaseClass
{
    public DerivedClass():base() { }

    protected override MyBase WorkField 
    { 
        get 
        { 
            return new MyExtend(); 
        }
    }

    //public new int WorkProperty
    //{
    //    get { return 0; }
    //}
}

您的子类的多态行为将允许您返回它。

答案 1 :(得分:1)

对于覆盖签名应该是基本方法。

public class BaseClass<T> where T : MyBase, new()
{
    public BaseClass() { }
    protected virtual T WorkField { get { return new T(); } }
    public int WorkProperty { get { return WorkField.Value; } }
}

public class DerivedClass : BaseClass<MyBase>
{
    public DerivedClass() : base() { }

//发生相同的错误,因为基本属性的类型为“MyBase”

  

protected override MyExtend WorkField {get {return new MyExtend();   }}

    //public new int WorkProperty
    //{
    //    get { return 0; }
    //}
}

答案 2 :(得分:0)

    public class BaseClass<T> where T: MyBase, new()
    {
        public BaseClass() { }
        protected virtual T WorkField { get { return new T(); } }
        public int WorkProperty { get { return WorkField.Value; } }
    }

    public class DerivedClass : BaseClass<MyExtend>
    {
        public DerivedClass() : base() { }
        protected override MyExtend WorkField { get { return new MyExtend(); } }

        //public new int WorkProperty
        //{
        //    get { return 0; }
        //}
    }

    public class MyBase
    {
        public MyBase()
        {

        }
        public int Value = 1;
    }
    public class MyExtend : MyBase
    {
        public int value = 20;
    }