开发者

Unable to cast an object of type "object {System.Collections.Generic.List<string[]>}" as 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 somethi开发者_开发技巧ng obvious but I cant figure it out.

It gives the exception -

Unable to cast object of type 'System.Collections.Generic.List1[System.String[]]' to type 'System.Collections.Generic.ICollection1[System.Object]'.


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


See Variance in Generic Interfaces

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜