百科问答小站 logo
百科问答小站 font logo



C# 中为什么List<List<T>> 不能转换为 IList<IList<T>> ? 第1页

  

user avatar   rednaxelafx 网友的相关建议: 
      

因为IList<T>的泛型参数T是invariant的,而不是题主所期待的covariant(或者说IList<out T>):

       public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable      

从 List<List<T>> 转成 IList<List<T>> 是完全没问题的,因为这个转换从泛型参数的角度看是invariant的。然而进一步转成 IList<IList<T>> 就不行了,因为把泛型参数中(内层)的 List<T> 转成 IList<T> 需要covariant。

传送门:

Covariance and Contravariance in Generics

具体到题主的例子,其实这样就好了:

       using System.Collections.Generic; using System.Linq;  class Record {   public List<Record> Data {     get { return null; }   } }  class Program {   static void Main(string[] args) {     var records = new List<Record>();     var casted1 = (IList<IList<Record>>)records.Select(r => r.Data as IList<Record>).ToList(); // ok     Console.WriteLine("cast1 succeeded.");     var casted2 = (IList<IList<Record>>)records.Select(r => r.Data).ToList<IList<Record>>(); // ok     Console.WriteLine("cast2 succeeded.");     var casted3 = (IList<IList<Record>>)records.Select(r => r.Data).ToList(); // fail     Console.WriteLine("cast3 succeeded.");   } }      

这是因为我的例子中,ToList()其实是个泛型方法,其泛型参数通常是被自动推导出来的;Record.Data的类型是List<Record>,于是用在那个ToList()调用时推导出来的就是ToList<List<Record>>。我们要么在Select()的时候就as一下来让Select推导出来的类型改变,要么直接在ToList()的地方指定清楚泛型参数,就好啦。




  

相关话题

  如何评价.NET Core 1.0称使用.NET Core运行速度是Node.js的八倍,Go的三倍? 
  C#中的String.Format()这两种写法那个更好? 
  C#异步方法返回Task的意义是什么?完整的TAP代码是什么结构? 
  有人号称编程零基础学C#4天,用记事本1分钟写个计算器,而且信誓旦旦,这是怎么回事? 
  为什么C# MVC5,DateTime属性默认的JSON解析值的格式为“/Date()/”? 
  为什么说try catch 隐藏了bug,C# try catch什么时候用? 
  Html.ActionLink怎么包裹其他代码? 
  .NET Core/.NET Framework 上的第三方常用类库/框架实现平均质量真的很差吗? 
  在程序里如何一本正经的胡说八道? 
  为什么叫.NET?它和C#是什么关系? 

前一个讨论
如何评价@左耳朵耗子 的《关于阿里云经典网络的问题》?
下一个讨论
为什么电子邮件允许冒充发件人?





© 2025-03-07 - tinynew.org. All Rights Reserved.
© 2025-03-07 - tinynew.org. 保留所有权利