2011-12-20 106 views
9

嘗試這樣的事情時,遇到了一個InvalidCastException:無法將列表<KeyValuePair <...,...>>轉換爲IEnumerable <object>?

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

回答

17

這是因爲KeyValuePair<K,V>是不是一類,是一個結構。要轉換列表中IEnumerable<object>將意味着你必須要每個鍵 - 值對和框它:

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

因爲你必須每個項目轉換列表中,你不能簡單地鑄造做到這一點列出它自己。

2

A KeyValuePair是一個結構體,不從類對象繼承。

3

首先字典已經是KeyValuePairs的集合,因此第二個示例是將整個Dictionary轉換爲對象,而不是KeyValuePairs。

無論如何,如果你想使用的列表中,您需要使用鑄造法的KeyValuePair結構轉換成一個對象:

IEnumerable<object> test = (IEnumerable<object>)new List<KeyValuePair<string, int>>().Cast<object>(); 
相關問題