不能't转换列表>IEnumerable< object>
本文关键字:KeyValuePair object IEnumerable 列表 转换 不能 | 更新日期: 2023-09-27 18:18:28
当尝试这样做时获得InvalidCastException:
IEnumerable<object> test = (IEnumerable<object>)new List<KeyValuePair<string, int>>();
然而,这确实有效:
IEnumerable<object> test = (IEnumerable<object>)new List<Dictionary<string, int>>();
那么最大的区别是什么呢?为什么KeyValuePair不能转换为对象?
更新:我应该指出这确实有效:
object test = (object)KeyValuePair<string,string>;
这是因为KeyValuePair<K,V>
不是一个类,而是一个结构体。要将列表转换为IEnumerable<object>
,意味着您必须将每个键值对框起来:
IEnumerable<object> test = new List<KeyValuePair<string, int>>().Select(k => (object)k).ToList();
由于必须转换列表中的每个项,因此不能通过简单地转换列表本身来实现。
因为它是一个结构体,而不是一个类:http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx
KeyValuePair
是一个结构体,不从类对象继承
首先Dictionary已经是一个集合的KeyValuePairs,因此第二个例子是将整个Dictionary转换为一个对象,而不是KeyValuePairs。
无论如何,如果您想使用List,您需要使用Cast方法将KeyValuePair结构转换为对象:
IEnumerable<object> test = (IEnumerable<object>)new List<KeyValuePair<string, int>>().Cast<object>();