首页 > 解决方案 > 列表> 结果 = 新列表>()

问题描述

这是我很长时间以来一直困惑的事情。不确定这是 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 行是正确的吗?

标签: c#oopgenericsarraylistinterface

解决方案


因为在

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>>(); 

推荐阅读