刚刚遇到这个:
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]
(加重)
提供的…子句排除实际隐含的转换.
原文地址:https://www.jb51.cc/csharp/97013.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。