百科问答小站 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()的地方指定清楚泛型参数,就好啦。




  

相关话题

  如何在c#应用程序里使用excel文件做数据源? 
  如何判断 string 是否为合法的 C# 变量名? 
  面向对象编程中, 接口既然不能直接描述方法, 要他有何用? 
  C# 中为什么List<List<T>> 不能转换为 IList<IList<T>> ? 
  为什么一说到 C#,很多人都说跟微软绑太紧,说到 Objective-C,就没人说跟苹果绑太紧呢? 
  实际开发中ref、out参数有多大作用? 
  C#如何将数据库一并打包发行? 
  .net开发都有哪些容易入手,轻量级的框架? 
  ADO.NET的SqlParameter(String, Object)的构造函数第二个参数不能为0? 
  .Net 为什么不为 Dictionary 提供 IEqualityComparer 的默认实现? 

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





© 2024-09-19 - tinynew.org. All Rights Reserved.
© 2024-09-19 - tinynew.org. 保留所有权利