无法将类型为“object {System.Collections.Generic.List <string []>}”的对象强制转换为ICollection <object> </object> </string []>

时间:2011-07-13 17:10:59

标签: c# .net

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

我确信它显而易见但我无法弄明白。

它给出了异常 -

  

无法投射类型的对象   'System.Collections.Generic.List 1[System.String[]]' to type 'System.Collections.Generic.ICollection 1 [System.Object的]'。

2 个答案:

答案 0 :(得分:4)

在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);

答案 1 :(得分:2)