鉴于:
public interface IMyInterface{ } public class MyClass:IMyInterface{ public MyClass(){} } public struct MyStruct:IMyInterface{ private int _myField; public MyStruct(int myField){_myField = myField;} }
为什么我可以写:
IEnumerable<IMyInterface> myClassImps = new[] { new MyClass(),new MyClass(),new MyClass() };
但不是:
IEnumerable<IMyInterface> myStructImps = new[]{ new MyStruct(0),new MyStruct(1),new MyStruct(2) };
这给我以下警告:
错误29无法将类型’MyApp.MyNS.MyStruct []’隐式转换为’System.Collections.Generic.IEnumerable< MyApp.MyNS.IMyInterface>‘
而且必须写成:
IEnumerable<IMyInterface> myStructImps = new IMyInterface[]{ new MyStruct(0),new MyStruct(2) };
解决方法
问题是数组协方差.
This specification谈论它:
For any two reference-types A and B,if an implicit reference conversion (Section 6.1.4) or explicit reference conversion (Section 6.2.3) exists from A to B,then the same reference conversion also exists from the array type A[R] to the array type B[R],where R is any given rank-specifier (but the same for both array types)
一个更简单的例子也是失败的
int[] c = new int[0]; object[] d = c;
而
string[] c = new string[0]; object[] d = c;
工作正常.你基本上是试图做同样的事情.您有一个值类型MyStruct的数组,并且您尝试将其隐式转换为IMyInterface,该数组协方差规范未涵盖.