我有以下代码:

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

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

这产生编译错误,我不知道我应该使用泛型类型的TestProperty以才达到在子类中具有不同类型的同名的我的目标?

有帮助吗?

解决方案

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

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

public class StringProperty : TestProperty<string>
{
}

有没有必要在这一点上覆盖 - 而事实上,除非你打算做别的,你可能也摆脱StringProperty的全部,只是使用TestProperty<string>

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top