简体   繁体   中英

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 something obvious but I cant figure it out.

It gives the exception -

Unable to cast object of type 'System.Collections.Generic.List 1[System.String[]]' to type 'System.Collections.Generic.ICollection 1[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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM