百科问答小站 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# 当年设计成一个彻底编译到机器码的但有运行时的 AOT 语言,能不能真的拿来代替 C++? 
  c#中,is或者as做类型转换是否影响效率,有必要缓存吗? 
  c# .net core 相比 java spring,如何选择? 
  为什么听说过 JVM 调优,却没听说过 CLR 调优? 
  作为非计算机专业的学生,觉得 C 语言远比其他语言易于上手,正常吗? 
  c#关于异步编程? 
  为什么微软建议超过64字节不要使用结构? 
  为什么 C# 发明 13 年之后微软才推出编译为本地代码的功能? 
  如果编程语言有性别?Java、C++、C、C#是男是女?是GAY还是LES? 
  C#每个类代码一大坨,有什么好的方能展示他的公有方法和属性? 

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





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