在满足接口(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/