加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – IEnumerable从类[]但不是从结构[].为什么?

发布时间:2020-12-15 18:00:21 所属栏目:百科 来源:网络整理
导读:鉴于: public interface IMyInterface{}public class MyClass:IMyInterface{ public MyClass(){}}public struct MyStruct:IMyInterface{ private int _myField; public MyStruct(int myField){_myField = myField;}} 为什么我可以写: IEnumerableIMyInterf
鉴于:
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,该数组协方差规范未涵盖.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读