以下代码示例:
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
这是编译器错误吗?如果不是,为什么我不允许这样做?
最佳答案
即使它是协变的,您也无法更改接口(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/