刚刚遇到这个:
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]
(加重)
提供的…子句排除实际隐含的转换.