【问题标题】:How to override the type of a member in abstract class in child class如何在子类的抽象类中覆盖成员的类型
【发布时间】:2010-12-01 17:02:35
【问题描述】:

我有以下代码:

public abstract class TestProperty
{
    public abstract Object PropertyValue { get; set; }
}

public class StringProperty: TestProperty
{
    public override string PropertyValue {get;set}
}

这会产生编译错误,我想知道我是否必须在 TestProperty 中使用泛型类型才能实现在子类中具有不同类型的同名目标?

【问题讨论】:

    标签: c# .net inheritance abstract-class covariance


    【解决方案1】:

    是的,C# 不支持协变返回类型。您确实可以在这里使用泛型:

    public abstract class TestProperty<T>
    {
        public abstract T PropertyValue { get; set; }
    }
    
    public class StringProperty : TestProperty<string>
    {
    }
    

    此时无需覆盖 - 事实上,除非您打算做其他任何事情,否则您不妨完全摆脱 StringProperty 并只使用 TestProperty&lt;string&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-09
      相关资源
      最近更新 更多