2009-05-25 21 views

回答

42

KeyValuePair < T,T>用於遍歷字典< T,T>。這是.Net 2(以及之後)的做事方式。

DictionaryEntry用於遍歷HashTables。這是.Net 1的做事方式。

下面是一個例子:

Dictionary<string, int> MyDictionary = new Dictionary<string, int>(); 
foreach (KeyValuePair<string, int> item in MyDictionary) 
{ 
    // ... 
} 

Hashtable MyHashtable = new Hashtable(); 
foreach (DictionaryEntry item in MyHashtable) 
{ 
    // ... 
} 
+4

KeyValuePair是泛型,另一個是泛型​​。建議前者使用前進。 – Gishu 2009-05-25 06:00:48

+1

我認爲他理解一個是泛型​​,一個是非泛型。我認爲他的問題是我們爲什麼需要兩個? – cdmckay 2009-05-25 19:49:22

90

KeyValuePair<TKey,TValue>代替DictionaryEntry被使用,因爲它是泛型。使用KeyValuePair<TKey,TValue>的好處是我們可以給編譯器提供更多關於我們字典中內容的信息。擴展Chris的例子(我們有兩個包含<string, int>對的字典)。

Dictionary<string, int> dict = new Dictionary<string, int>(); 
foreach (KeyValuePair<string, int> item in dict) { 
    int i = item.Value; 
} 

Hashtable hashtable = new Hashtable(); 
foreach (DictionaryEntry item in hashtable) { 
    // Cast required because compiler doesn't know it's a <string, int> pair. 
    int i = (int) item.Value; 
}