界面协方差问题

Grz*_*man 5 covariance c#-4.0

以下代码示例:

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
{
}
Run Code Online (Sandbox Code Playgroud)

无法编译(在VS2010 SP1下),出现以下错误:

Error   4   'C' does not implement interface member 'I<J>.GetT()'
Run Code Online (Sandbox Code Playgroud)

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

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

Eth*_*iac 2

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

interface Animal
{
    Animal GetAnimal();
}

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

   //Allowed
   Animal GetAnimal()
   {
       return this;
   }   
}
Run Code Online (Sandbox Code Playgroud)

问题是 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
{
}
Run Code Online (Sandbox Code Playgroud)