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

c# – 将列表对象列入列表vs IList,第1张

概述刚刚遇到这个: Func<List<object>> foo = () => new List<object>();List<string> s = (List<string>)foo();IList<string> s1 = (IList<string>)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]

(加重)

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

总结

以上是内存溢出为你收集整理的c# – 将列表对象列入列表vs IList全部内容,希望文章能够帮你解决c# – 将列表对象列入列表vs IList所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/1237236.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存