2009-05-25 3 views
96

汎用バージョンであるKeyValuePairとDictionaryEntryの違いは何ですか?KeyValuePair VS DictionaryEntry

generic DictionaryクラスのDictionaryEntryではなくKeyValuePairが使用される理由は何ですか?

答えて

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はGenericsであり、もう1つは事前ジェネリックです。前者の使用はfwdをお勧めします。 – Gishu

+1

私は彼がジェネリック医薬品のためのものであり、非ジェネリック医薬品のためのものであると理解していると思います。私は彼の質問がなぜ両方必要なのかと思います。 – cdmckay

+1

もし彼が求めているのであれば、実際には両方とも必要ではありません。ネット2まではジェネリックは利用できず、後方互換性のためにジェネリックではないものを残しました。一部の人々はまだ非一般的なものを使用したいかもしれませんが、それは強く推奨されません。 – Chris

90

KeyValuePair<TKey,TValue>DictionaryEntryの代わりに使用されます。 KeyValuePair<TKey,TValue>を使用する利点は、私たちが辞書にあるものについてより多くの情報をコンパイラに与えることができることです。 Chrisの例(2つの辞書に<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; 
} 
+66

+1 "generified"です。それは言葉ですか? :-p – BFree

+3

確かに一般化されていますか? – danielcooperxyz

+14

確かにジェネリック化されているか、ジェネリック化されているか(yankeefied) –

関連する問題