2012-05-01 50 views

回答

7

我認爲這是相當簡單的投一個IDictionary<TKey, IList<TValue>>對象的IDictionary<TKey, IEnumerable<TValue>>

絕對不是。它不會是類型安全的。這也是爲什麼不是一個例子:

// This is fine... 
IDictionary<string, IList<int>> dictionary = new Dictionary<string, IList<int>>(); 

// Suppose this were valid... 
IDictionary<string, IEnumerable<int>> badDictionary = dictionary; 

// LinkedList<T> doesn't implement IList<T> 
badDictionary["foo"] = new LinkedList<int>(); 

// What should happen now? 
IList<int> bang = dictionary["foo"]; 

正如你所看到的,那將導致問題 - 我們會試圖獲得LinkedList<int>出來的時候,我們希望所有的值來實現IList<int>。泛型的要點是要保證類型安全 - 那麼哪一行你會期望失敗?第一,第三和第四線看起來很清晰有效的給我 - 所以第二個是唯一的一個能不能編譯,它...

現在一些箱子,也可以是安全地完成。例如,您可以將(在C#4中)從IEnumerable<string>轉換爲IEnumerable<object>,因爲IEnumerable<T>只在「輸出」位置使用T

查看MSDN瞭解更多詳情。

編輯:只是爲了澄清 - 很容易創建一個新的字典與現有的鍵/值對副本,例如,使用鏈接:

var copy = original.ToDictionary<TKey, IEnumerable<TValue>>(pair => pair.Key, 
                  pair => pair.Value); 

你只需要知道你現在有兩個單獨的字典。

+0

那麼這對我來說沒有任何意義。 'IEnumerable <>'不會從'IList <>'繼承,反過來,這顯然是錯誤的。你可以投下祖先,而不是後代,對嗎?那麼這是如何使無效下降? –

+0

@JeremyHolovacs:我的示例試圖正確*做你聲稱想做的事:將一個IDictionary >轉換爲一個'IDictionary >'。如果這不是你想要做的,你應該澄清你的問題。 –

+0

最後一行似乎並不完全相同;在那裏你似乎試圖將'IEnumerable '轉換爲'IList ',這對我來說顯然是錯誤的。將IList 轉換爲IEnumerable 似乎應該完全合法,因爲IList從IEnumerable繼承。 –

0

這可能會也可能不會幫助你,但我想我會把它作爲Jon的答案的補充。

如果你需要的是字典的,沒有提及自己的鑰匙,你可以這樣做:

IDictionary<TKey, IList<TValue>> dictionary = Whatever(); 
var values = (IEnumerable<IEnumerable<TValue>>)dictionary.Values; 

對於這個工作,你必須使用C#4.0或更高版本,TValue絕被限制爲一個參考類型。這裏的代碼,略有重構,並附註釋說明:

IDictionary<TKey, IList<TValue>> dictionary = Whatever(); 

//Values returns an ICollection<IList<TValue>> 
ICollection<IList<TValue>> temp1 = dictionary.Values; 

//ICollection<T> inherits from IEnumerable<T> 
IEnumerable<IList<TValue>> temp2 = temp1; 

//IEnumerable<T> is covariant 
//There is an implicit reference conversion between IList<T> and IEnumerable<T> 
//So there is an implicit reference conversion between IEnumerable<IList<T>> 
//and IEnumerable<IEnumerable<T>> 
IEnumerable<IEnumerable<TValue>> values = temp2; 
相關問題