简体   繁体   中英

Can't convert List<KeyValuePair<...,...>> to IEnumerable<object>?

Getting an InvalidCastException when trying something like this :

IEnumerable<object> test = (IEnumerable<object>)new List<KeyValuePair<string, int>>();

However, this did work:

IEnumerable<object> test = (IEnumerable<object>)new List<Dictionary<string, int>>();

So what's the big difference? Why can a KeyValuePair not be converted to an object?

Update : I should probably point out that this did work:

object test = (object)KeyValuePair<string,string>;

That's because KeyValuePair<K,V> is not a class, is a struct. To convert the list to IEnumerable<object> would mean that you have to take each key-value pair and box it:

IEnumerable<object> test = new List<KeyValuePair<string, int>>().Select(k => (object)k).ToList();

As you have to convert each item in the list, you can't do this by simply casting the list itself.

因为它是一个结构,而不是一个类:http: //msdn.microsoft.com/en-us/library/5tbh8a42.aspx

KeyValuePair是一个结构,不从类对象继承。

First of all Dictionary is already a collection of KeyValuePairs, therefore the second example is casting the entire Dictionary to an object, not the KeyValuePairs.

Anyway, if you want to use the List, you need to use the Cast method to convert the KeyValuePair structure into an object:

IEnumerable<object> test = (IEnumerable<object>)new List<KeyValuePair<string, int>>().Cast<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