回答:
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;
}
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)
{
// ...
}