KeyValuePair VS DictionaryEntry


116

ジェネリックバージョンであるKeyValuePairとDictionaryEntryの違いは何ですか?

ジェネリックディクショナリクラスで、DictionaryEntryの代わりにKeyValuePairが使用されるのはなぜですか?

回答:


108

KeyValuePair<TKey,TValue>DictionaryEntry汎用化されているため、代わりに使用されます。aを使用する利点はKeyValuePair<TKey,TValue>、辞書に何があるかについての詳細情報をコンパイラーに提供できることです。Chrisの例(<string, int>ペアを含む2つの辞書がある)を拡張します。

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

4
確かにそれは一般化されていますか?
danielcooperxyz 2013

26
確かに一般化されている(limeyfied)、または一般化されている(yankeefied)
jenson-button-event

7
あなたが探している言葉は一般化されています。;)
Jason

5
一般化されていない、より一般的な一般化
TheGeekZn '13 / 08/15

2
ジェネリックと言うのは私だけですか?
Mauro Sampietro 2016年

51

KeyValuePair <T、T>は、Dictionary <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つはpre-genericsです。前者を使用することをお勧めします。
岐阜市

1
1つはジェネリック医薬品用であり、1つはジェネリック医薬品以外のものであることを彼は理解していると思います。彼の質問は、なぜ両方が必要なのでしょうか?
cdmckay 2009年

3
それが彼が求めていることなら、まあ、私たちは本当に両方を必要としません-ジェネリックは.net 2まで利用できなかっただけで、非ジェネリックのものを後方互換性のために残しました。一部の人々はまだ非ジェネリックのものを使用したいかもしれませんが、強くお勧めしません。
クリス

この答えは私にはもっと理にかなっています。
Merin Nakarmi 2017
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.