为什么我不能实现一个接口,这条路? [英] Why can't I implement an Interface this way?
问题描述
可能重复:结果
的是否支持C#返回类型的协方差?
我不知道如果我只是愚蠢...
I'm not sure if I'm just being stupid...
如果我有一个接口:
public interface IMoop
{
object Moop();
}
为什么我不能实现它,像这样(我想这将使用隐?协方差)
Why can't I implement it like so (I guess this would use implicit Covariance?)
public class MoopImplementor : IMoop
{
string Moop();
}
MoopImplementor的任何实例将满足IMoop规定的合同,所以它看起来像。这应该是确定
Any instance of MoopImplementor would meet the contract specified by IMoop, so it seems like this should be ok.
请赐教:)
编辑:要自实现类在清返回的东西,从接口方法的返回类型继承 - 我觉得这应该工作。具体来说,一个字符串
是对象
。 (和同样适用于其他任何inhertiance链)。
To be clear- since the implementing class returns something that inherits from the return type of the Interfaced method - I feel this should work. Specifically, a string
IS an object
. (and the same goes for any other inhertiance chain).
推荐答案
C#不支持的返回类型的协方差接口实现的或虚拟的方法overrding的目的。详情请参见这个问题:
C# does not support return type covariance for the purposes of interface implementation or virtual method overrding. See this question for details:
C#不支持的通用协方差和接口逆变和委托是类型构建wtih引用类型的类型参数的为C#4。
C# does support generic covariance and contravariance of interfaces and delegate types that are constructed wtih reference types for the type arguments as of C# 4.
和C#不支持的返回类型的协方差的时候的转换一个返回引用类型的委托类型,其返回类型是兼容的引用类型的方法。的(而且同样支持参数类型的逆变的。)
And C# does support return type covariance when converting a method that returns a reference type to a delegate type whose return type is a compatible reference type. (And similarly it supports parameter type contravariance.)
如果这个问题你感兴趣,我已经写了许多文章讨论了方差C#不和不支持的各种版本。见
If this subject interests you, I have written a great many articles discussing various versions of variance that C# does and does not support. See
https://blogs.msdn.microsoft.com/ericlippert/tag/covariance-and-contravariance/
有关详细信息。
这篇关于为什么我不能实现一个接口,这条路?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!