c#-4.0 - 接口(interface)协方差问题

标签 c#-4.0 covariance

以下代码示例:

interface I<out T>
    where T : class, I<T>
{
    T GetT();
}

interface J : I<J>
{
}

abstract class B<T> : I<T>
    where T : B<T>
{
    T I<T>.GetT()
    {
        return null;
    }
}

class C : B<C>, J
{
}

无法编译(在带有 SP1 的 VS2010 下)并出现以下错误:
Error   4   'C' does not implement interface member 'I<J>.GetT()'

但是,C 确实实现了(通过其基 B)I,由于 I 被声明为协变,它也应该捕获 I(如 C:J)。

这是编译器错误吗?如果不是,为什么我不允许这样做?

最佳答案

即使它是协变的,您也无法更改接口(interface)的返回类型。这与非泛型类中的协方差没有什么不同。

interface Animal
{
    Animal GetAnimal();
}

class Cat : Animal
{
   //Not ALlowed
   Cat GetAnimal()
   {
       return this;
   }

   //Allowed
   Animal GetAnimal()
   {
       return this;
   }   
}

问题是 C 作为 B<C> 的特化返回 C I<C>.GetT() , 但是 J 的规范需要 J GetT() .

尝试以下操作:
interface I<out T>
    where T : class, I<T>
{
    T GetT();
}

interface J : I<J>
{
}

abstract class B<T,U> : I<U>
    where T : B<T,U>, U
    where U : class, I<U>
{
    U I<U>.GetT()
    {
        return null;
    }
}

class C : B<C,J>, J
{
}

关于c#-4.0 - 接口(interface)协方差问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6250676/

相关文章:

c# - 如何在 C#(4.0) 中存储键/值对?

asp.net - 显示错误填充 : SelectCommand. 连接属性尚未初始化

c# - 哪些语言支持继承方法返回类型的协变?

Scala 列表 : Why does this List operation work?

c#-4.0 - 如何强制 Entity Framework 不要查询为 sp_executesql

c# - 如何使用使用 sha1ecdsa 的公钥根据签名验证数据?

.net - COM 互操作 : indexed property signature issues

c# - out 关键字如何与类型协方差相关联?

python - 在 pandas 中创建滚动协方差矩阵

c# - 从 x 到 y 的协变数组转换可能会导致运行时异常