//无法将类型"System.Collections.Generic.List<System.Collections.Generic.List<int>>”隐式转换为"System.Colections.Generic.list<System.Colections.Generic.list<int>>"。
IList <IList<int>> list = new List<List<int>>();
写到这样一行代码时,发现编辑器报错了:
CS0266:无法将类型"System.Collections.Generic.List<System.Collections.Generic.List<int>>”隐式转为"System.Colections.Generic.list<System.Colections.Generic.list<int>>"。
第一反应还看不出哪里出错了,查阅了一下资料发现应该这样写:
IList<IList<int>> list = new List<IList<int>>();
//或者
List<List<int>> list = new List<List<int>>();
原因:
对于 IList<IList<int>> list = new List<List<int>>(); 来说:
-
左侧声明:
IList<IList<int>>IList<IList<int>>表示一个泛型嵌套的接口类型:- 外层是
IList<T>类型。 - 内层是
IList<int>类型。
- 外层是
- 它要求 list 是一个实现
IList接口的集合,且其中的元素是实现IList<int>的集合。
-
右侧实例化:
new List<List<int>>()- 这里创建了一个嵌套的
List<List<int>>对象:- 外层是
List<T>类型。 - 内层是
List<int>类型。
- 外层是
- 这里创建了一个嵌套的
-
为什么不合法?
-
虽然 List<int>是IList<int>的实现类,但泛型不支持隐式转换。换句话说,尽管List<T>实现了IList<T>接口,但泛型类型参数在赋值时必须完全匹配。这里,IList<IList<int>>和List<List<int>>中的泛型参数IList<int>和List<int>不完全匹配。
954

被折叠的 条评论
为什么被折叠?



