如何覆盖子类中抽象类中成员的类型

qin*_*ong 1 .net c# inheritance abstract-class covariance

我有以下代码:

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

public class StringProperty: TestProperty
{
    public override string PropertyValue {get;set}
}
Run Code Online (Sandbox Code Playgroud)

哪个生成编译错误,我想我是否应该在TestProperty中使用泛型类型以实现我在子类中具有不同类型的同名的目标?

Jon*_*eet 6

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

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

public class StringProperty : TestProperty<string>
{
}
Run Code Online (Sandbox Code Playgroud)

在这一点上没有必要覆盖 - 事实上,除非你要做任何其他事情,否则你可能StringProperty完全摆脱并且只是使用TestProperty<string>.