Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/267.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
简单协方差不';它似乎无法处理c#泛型_C#_Generics_Inheritance_Covariance - Fatal编程技术网

简单协方差不';它似乎无法处理c#泛型

简单协方差不';它似乎无法处理c#泛型,c#,generics,inheritance,covariance,C#,Generics,Inheritance,Covariance,在我看来,我对c#中的协方差有一个理解上的问题。 如果我有以下课程: class a { } class b : a { } class A<T> where T: a { } class B<T> : A<T> { } class C : A<b> { } a类{ } b类:a{ } A类,其中T:A{ } B类:A{ } 丙类:甲{ } 现在我做到了: A<a> t1 = new B<b>(); A<a

在我看来,我对c#中的协方差有一个理解上的问题。 如果我有以下课程:

class a {
}

class b : a {
}

class A<T> where T: a {
}

class B<T> : A<T> {
}

class C : A<b> {
}
a类{
}
b类:a{
}
A类,其中T:A{
}
B类:A{
}
丙类:甲{
}
现在我做到了:

A<a> t1 = new B<b>();
A<a> t2 = new C();
A

为什么这个非常简单的例子不起作用


致以最诚挚的问候

协方差的工作原理与您描述的一样,但有一点很重要:

泛型类只有从接口继承时才是协变的 在协变泛型参数上用“out”关键字标记

关于如何使用,有很多规则,请参阅以了解详细信息

您没有继承协变接口,因此派生的赋值将中断

你需要像这样的东西:

IGeneric<out T>
{
}

class a<T> : IGeneric<T>
{
}
IGeneric
{
}
a类:智能型
{
}
等等。您的作业应该有效,只要它看起来像:

IGeneric<Base> = a<Derived>
IGeneric=a

只要任务看起来是:IGeneric=aTotally correct,编辑为include,任务就应该有效。非常感谢你!问了几次:或者