c# - 列表> 结果 = 新列表>()
问题描述
这是我很长时间以来一直困惑的事情。不确定这是 C# 特定问题还是我无法掌握的一些简单的 OOP 事实。
IList<IList<int>> result = new List<IList<int>>(); //Works Fine
IList<IList<int>> result2 = new IList<IList<int>>(); //Gives Error because we cannot initialize interface
IList<IList<int>> result3 = new List<List<int>>(); //Gives Error please explain why
IList<IList<int>> result4 = new IList<List<int>>(); //Gives Error please explain why
对于上面的代码行,有人可以解释为什么第 3 行和第 4 行是错误的,而第 1 行是正确的吗?
解决方案
因为在
R<S> = T<U>;
T : R
. 你所有的例子都满足这一点。List : IList
,List = List
, 和IList = IList
.T : new()
. 这将取消 2 和 4 中的接口的资格。U = S
. 泛型类型必须匹配,不能派生。这取消了3的资格。
因为 U = S,所以写成这样
R<S> = new T<S>;
然后就更清楚了。这四个将满足上述要求
IList<IList<int>> result = new List<IList<int>>();
List<IList<int>> result2 = new List<IList<int>>();
IList<List<int>> result3 = new List<List<int>>();
List<List<int>> result4 = new List<List<int>>();
推荐阅读
- .net-core - 是否有用于 gRPC 的 .net 核心全局工具?
- java - Spark 无法分配请求的地址:服务驱动程序在 16 次重试后失败
- javascript - Javascript - 相等时间timesetouts - 即使javascript是单线程的,执行的随机顺序?
- html - Django CMS:如何在 CMS 中放置一个按钮以保留链接
- c++ - 以现代 CMake 方式控制包含库中的构建选项(测试等)
- mongodb - 不能在 Spring Boot 测试中使用 @Transactional
- angular - Angular6 升级问题:“对象”类型上不存在属性“数据”
- mysql - 从第一个表到第二个表引用多个行ID,以便每次都可以显示第一个表中的所有行
- bash - Bash:蜘蛛模式下的 wget 不输出任何内容
- docker - Traefik + 码头工人。www.domain.tld 有效,domain.tld 无效