Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/303.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_Covariance - Fatal编程技术网

泛型类中的C#-数组协方差

泛型类中的C#-数组协方差,c#,generics,covariance,C#,Generics,Covariance,我知道C#支持如下数组中的协方差: object[] array = new string[3]; 但是当它试图编译下面的代码时,我得到了一个错误 class Dummy<K,T> where T:K { public void foo() { K[] arr = new T[4]; } } 类虚拟,其中T:K { 公共图书馆 { K[]arr=新的T[4]; } } 它表示“无法将类型“T[]”隐式转换为“K[]”” 为什么我会犯这个错

我知道C#支持如下数组中的协方差:

object[] array = new string[3];
但是当它试图编译下面的代码时,我得到了一个错误

class Dummy<K,T> where T:K
{
    public void foo()
    {
        K[] arr = new T[4];
    }
}
类虚拟,其中T:K
{
公共图书馆
{
K[]arr=新的T[4];
}
}
它表示“无法将类型“T[]”隐式转换为“K[]””


为什么我会犯这个错误

类型T必须支持到K的隐式转换

T a=新的T(); kb=a


必须有效。

必须指定T和K都是引用类型。数组协方差仅适用于引用类型。将声明更改为:

class Dummy<K,T> where T : class, K
类虚拟,其中T:class,K

而且效果很好。您不必指定K是引用类型,因为如果t是引用类型并且它派生或实现了K,那么K也必须是引用类型。(至少我假设这就是原因。为了清楚起见,在其中添加
K:class
也没有什么坏处。)

隐式转换端由t:K部分指定。看看我的答案有什么遗漏。