无法转换类型为"object {System.Collections.Generic.List< string []>}}"的对象;作为ICollection< object> [英] Unable to cast an object of type "object {System.Collections.Generic.List<string[]>}" as ICollection<object>

查看:89
本文介绍了无法转换类型为"object {System.Collections.Generic.List< string []>}}"的对象;作为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.List1[System.String[]]' to type 'System.Collections.Generic.ICollection1[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&lt; string []&gt;}}"的对象;作为ICollection&lt; object&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆