以下代码示例:
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&lt; C&gt;)I&lt; C&gt;,由于我被声明为协变,它应该捕获I&lt; J&gt;。 (以及C:J)。
这是编译器错误吗?如果没有,为什么我不被允许这样做?
答案 0 :(得分:2)
即使它是协变的,你也无法改变界面的返回类型。这与非通用类中的协方差没有什么不同。
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
{
}