Why does this inheritance hierarchy not permit this assignment?
I have the following complex inheritance hierarchy:
I1<I3>
A1 : C1, I2
C2 : A1, I3
C3 : A2<C2>, I4
A2<C2> : I5, I1<C2>
In picture form:
Writing:
I1<I3> i = new C3();
...results in the compilation error "Cannot convert source type... 开发者_运维问答to target type...".
Why?
Covariant and contravariant generic parameters should be explicitly marked as such.
The following code compiles without error (note the out keyword):
class tmp
{
class C1 {}
interface I2 {}
interface I3 {}
interface I4 {}
interface I5 {}
interface I1<out I3> {}
class A1 : C1, I2 {}
class C2 : A1, I3 {}
class C3 : A2<C2>, I4 {}
class A2<C2> : I5, I1<C2> { }
private void Main()
{
I1<I3> i = new C3();
}
}
Of course, without the out keyword it fails with the same error message as you described.
精彩评论