C# 接口(interface)和类型伪装

标签 c# inheritance interface

在满足接口(interface)要求时,我的子类似乎无法伪装成基类。例如:

class MyBaseClass
{}

class MySubClass : MyBaseClass
{}

interface MyInterface
{
    MyBaseClass someFunction();
}

class MyImplementation : MyInterface
{
    public MySubClass someFunction() { return null; }
}

生成以下错误:

'MyNamespace.MyImplementation' does not implement interface member 'MyNamespace.MyInterface.someFunction()'. 'MyNamespace.MyImplementation.someFunction()' cannot implement 'MyNamespace.MyInterface.someFunction()' because it does not have the matching return type of 'MyNamespace.MyBaseClass'.

这也是需要接口(interface)与实现的问题。例如,如果我有一个带有返回 IList 的函数的接口(interface),我的实现不能返回一个 List - 它必须返回一个 IList。

我是在做错什么还是这是 C# 接口(interface)的限制?

最佳答案

C# 不支持协变返回类型。实现接口(interface)时,必须返回接口(interface)指定的类型。如果需要,您可以显式实现该接口(interface)并使用另一个具有相同名称的方法来返回子类型。例如:

class MyImplementation : MyInterface
{
    MyBaseClass MyInterface.someFunction() { return null; }
    public MySubClass someFunction() { return null; }
}

关于C# 接口(interface)和类型伪装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1924441/

相关文章:

c# - Webservice 无法序列化,因为它没有无参数构造函数

c# - 使用日期条件从 Varchar Col 提取数据时出现问题

c# - C#中的应用程序启动

php - 根据对方法的外部或内部调用选择性地公开函数

python - 从集合继承。计数器: 'fromkeys' is abstract

c# - Entity-framework-7 将 Fluent API 配置组织到一个单独的类中

c++ - 全部继承自同一类的对象映射,调用对象方法而不是父类;由 小码哥发布于

java - 我无法从扩展 List 接口(interface)的类中调用方法

c# - 从接口(interface)强制执行可序列化而不强制类在 C# 中自定义序列化

java - 为什么createStatement方法是在Connection接口(interface)而不是Statement接口(interface)下声明的?