如何在C#中子类的重写方法中返回子类型?
收藏

我有一个带有重写方法的子类,我知道它总是返回基类中声明的返回类型的特定子类型。如果以这种方式编写代码,它将无法编译。由于那可能没有意义,所以让我举一个代码示例:

class BaseReturnType { }
class DerivedReturnType : BaseReturnType { }

abstract class BaseClass {
    public abstract BaseReturnType PolymorphicMethod();
}

class DerivedClass : BaseClass {
    // Compile Error: return type must be 'BaseReturnType' to match 
    // overridden member 'BaseClass.PolymorphicMethod()'
    public override DerivedReturnType PolymorphicMethod() { 
        return new DerivedReturnType(); 
    }
}

Is there any way to accomplish this in C#? If not, what's the best way to achieve something similar? And why isn't it allowed? It doesn't seem to allow any logical inconsistency, since any object returned from the over-ridden method still is BaseReturnType. Maybe there is something I hadn't considered though. Or maybe the reason is technological or historical.

最佳答案

不幸的是,不,协变返回类型在C#中不支持方法覆盖。 (同上转换参数类型。)

如果要实现接口,则可以使用“弱”版本显式实现它,还可以提供具有更强合同的公共版本。对于父类的简单覆盖,恐怕您没有这么奢侈:(

(编辑:Marc有一个合理的解决方案-尽管它很丑陋,并且方法隐藏对于可读性通常是一件坏事。没有冒犯的意思,Marc;)

我相信这实际上是CLR限制,而不仅仅是语言限制-但我完全有可能错了。

(从历史上看,Java(语言)在1.5之前一直有相同的限制-但它与泛型同时获得了协方差。)

    公众号
    关注公众号订阅更多技术干货!