无法转换类型为"object {System.Collections.Generic.List< string []>}}"的对象;作为ICollection< object> [英] Unable to cast an object of type "object {System.Collections.Generic.List<string[]>}" as ICollection<object>
问题描述
为什么不能在运行时将类型为 object {System.Collections.Generic.List< string []>}
类型的对象转换为 ICollection< object>
>?
Why can you not cast a object which at runtime has type object {System.Collections.Generic.List<string[]>}
as an ICollection<object>
?
我确定它很明显,但是我无法弄清楚.
I'm sure its something obvious but I cant figure it out.
它给出了例外-
无法转换类型的对象键入"System.Collections.Generic.List
1 [System.String []]"'System.Collections.Generic.ICollection
1 [System.Object]'.
Unable to cast object of type 'System.Collections.Generic.List
1[System.String[]]' to type 'System.Collections.Generic.ICollection
1[System.Object]'.
推荐答案
在C#4.0之前,泛型不是协变的.如果您不使用C#4.0,则可以像这样完成转换:
Before C# 4.0, generics are not covariant. If you are not using C# 4.0, you can accomplish this cast like this:
List<string[]> list = new List<string[]>();
//...Fill the list...
ICollection<object> collection = list.ConvertAll<object>(item => item as object);
这篇关于无法转换类型为"object {System.Collections.Generic.List< string []>}}"的对象;作为ICollection< object>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!