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

刚刚遇到这个:
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]

(加重)

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

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...