【问题标题】:Unable to cast an object of type "object {System.Collections.Generic.List<string[]>}" as ICollection<object>无法将“object {System.Collections.Generic.List<string[]>}”类型的对象转换为 ICollection<object>
【发布时间】:2011-10-04 16:46:35
【问题描述】:

为什么不能将运行时类型为object {System.Collections.Generic.List&lt;string[]&gt;} 的对象转换为ICollection&lt;object&gt;

我确定它很明显,但我无法弄清楚。

它给出了例外 -

无法转换类型的对象 'System.Collections.Generic.List1[System.String[]]' to type 'System.Collections.Generic.ICollection1[System.Object]'。

【问题讨论】:

标签: c# .net


【解决方案1】:

【讨论】:

    【解决方案2】:

    在 C# 4.0 之前,泛型不是协变的。如果你没有使用 C# 4.0,你可以像这样完成这个转换:

    List<string[]> list = new List<string[]>();
    //...Fill the list...
    ICollection<object> collection = list.ConvertAll<object>(item => item as object);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多