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

c# – 将列表对象列入列表vs IList

发布时间:2020-12-15 17:48:24 所属栏目:百科 来源:网络整理
导读:刚刚遇到这个: FuncListobject foo = () = new Listobject();Liststring s = (Liststring)foo();IListstring s1 = (IListstring)foo(); 编译器抱怨投射到列表(有意义),但对IList毫无意义.让我想知道为什么会这样? 解决方法 编译器知道List X不能是列表 Y.
刚刚遇到这个:
Func<List<object>> foo = () => new List<object>();
List<string> s = (List<string>)foo();
IList<string> s1 = (IList<string>)foo();

编译器抱怨投射到列表(有意义),但对IList毫无意义.让我想知道为什么会这样?

解决方法

编译器知道List< X>不能是列表< Y>.
因此,它会给出一个编译器错误.

但是,如果List< X>实际上也是实现IList< Y>的派生类.

如果两个类型都不是一个接口,或者一个类型是不相关的接口,而另一个类型是封闭的(或者一个结构体),那么只能从一个转换中得到一个编译时错误.

引用规范(§6.4.2)

The explicit reference conversions are:

  • From object and dynamic to any other reference-type.
  • From any class-type S to any class-type T,provided S is a base class of T.
  • From any class-type S to any interface-type T,provided S is not sealed and provided S does not implement T.
  • From any interface-type S to any class-type T,provided T is not sealed or provided T implements S.
  • From any interface-type S to any interface-type T,provided S is not derived from T.
  • [snip]

(加重)

提供的…子句排除实际隐含的转换.

(编辑:李大同)

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

    推荐文章
      热点阅读