Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Inheritance 为什么此继承层次结构不允许此分配?_Inheritance_C# 4.0_Covariance - Fatal编程技术网

Inheritance 为什么此继承层次结构不允许此分配?

Inheritance 为什么此继承层次结构不允许此分配?,inheritance,c#-4.0,covariance,Inheritance,C# 4.0,Covariance,我有以下复杂的继承层次结构: I1<I3> A1 : C1, I2 C2 : A1, I3 C3 : A2<C2>, I4 A2<C2> : I5, I1<C2> I1 A1:C1,I2 C2:A1,I3 C3:A2,I4 A2:I5,I1 图片形式: 写作: I1<I3> i = new C3(); i1i=newc3(); …导致编译错误“无法将源类型…转换为目标类型…” 为什么?协变和逆变

我有以下复杂的继承层次结构:

I1<I3>
A1 : C1, I2
C2 : A1, I3
C3 : A2<C2>, I4                
A2<C2> : I5, I1<C2>
I1
A1:C1,I2
C2:A1,I3
C3:A2,I4
A2:I5,I1
图片形式:

写作:

I1<I3> i = new C3();
i1i=newc3();
…导致编译错误“无法将源类型…转换为目标类型…”


为什么?

协变和逆变通用参数应明确标记为协变和逆变通用参数

以下代码编译无误(请注意out关键字):

类tmp
{
类别C1{}
接口I2{}
接口I3{}
接口I4{}
接口I5{}
接口I1{}
A1类:C1,I2{}
类别C2:A1,I3{}
类别C3:A2,I4{}
A2类:I5,I1{}
私有void Main()
{
I1 i=新的C3();
}
}

当然,如果没有out关键字,它将失败,并显示与您描述的相同的错误消息。

I3不是一种类型,因此不能用作泛型类型?I3是一种接口。C2实现I3,因此是协变的。C3实现I1,它通过协方差也是I1。因此我应该能够在问题中写下这句话吗?很明显我有个误会。。。
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();
    }
}