为什么 IList<IList<int>> 不等于 List<List<int>> ?

//无法将类型"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> 不完全匹配。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值