接口协方差问题 [英] interface covariance issue

查看:176
本文介绍了接口协方差问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码示例:

  interface I< out T& 
其中T:类,I< T>
{
T GetT();
}

interface J:I<
{
}

抽象类B< T> :I T
其中T:B< T>
{
T I< T> .GetT()
{
return null;
}
}

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

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

 错误4'C'不实现接口成员'I< J> .GetT()'



然而,C实现(通过其基本B C)I C,由于I被声明为协变,I C应该捕获I J。 (如C:J)。



这是一个编译器错误吗?

解决方案

即使它是协变的,你也不能改变返回接口类型。这与非泛型类中的协方差没有区别。

 接口Animal 
{
Animal GetAnimal ();
}

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

//允许
动物GetAnimal()
{
return this;
}
}

问题是C作为< c $ c> C 返回 C I C.GetT(),但是J的规范要求 J GetT()



请尝试以下操作:

  interface I< out T> 
其中T:类,I< T>
{
T GetT();
}

interface J:I<
{
}

抽象类B< T,U> :I U
其中T:B ,U
其中U:class,I<
{
U I< U> .GetT()
{
return null;
}
}

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


The following code sample:

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
{
}

fails to compile (under VS2010 with SP1) with the following error:

Error   4   'C' does not implement interface member 'I<J>.GetT()'

However, C does implement (through its base B<C>) I<C>, which, due to I being declared covariant, should capture I<J> as well (as C : J).

Is this a compiler bug? If not, why am I not allowed to do that?

解决方案

Even though it is covariant, you cannot change the return type of the interface. This is no different from the covariance in non-Generic classes.

interface Animal
{
    Animal GetAnimal();
}

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

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

The problem is that C as a specialization of B<C> returns C I<C>.GetT(), however the specification of J requires J GetT().

Try the following:

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
{
}

这篇关于接口协方差问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆