开发者

Why does this inheritance hierarchy not permit this assignment?

开发者 https://www.devze.com 2023-02-10 05:54 出处:网络
I have the following complex inheritance hierarchy: I1<I3> A1 : C1, I2 C2 : A1, I3 C3 : A2<C2>, I4

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:

Why does this inheritance hierarchy not permit this assignment?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消