有没有办法在C#中覆盖返回类型?如果有,如何覆盖?如果没有,为什么,以及推荐的方法是什么?
我的情况是我有一个具有抽象基类和派生类的接口。我想这样做(好吧,不是真的,但作为一个例子!):
public interface Animal
{
Poo Excrement { get; }
}
public class AnimalBase
{
public virtual Poo Excrement { get { return new Poo(); } }
}
public class Dog
{
// No override, just return normal poo like normal animal
}
public class Cat
{
public override RadioactivePoo Excrement { get { return new RadioActivePoo(); } }
}
RadioactivePoo
当然是从Poo
继承而来的。
我希望这样做是为了让那些使用Cat
对象的人能够使用Excrement
属性,而不必将Poo
转换为RadioactivePoo
,例如,Cat
仍然可以是Animal
列表的一部分,用户可能不知道或不关心它们的放射性粪便。希望这有意思...
就我所看到的,编译器至少不允许这样做。所以我猜这是不可能的。但你会推荐什么解决方案呢?