Відповіді:
KeyValuePair<TKey,TValue>використовується замість того, DictionaryEntryщо він узагальнений. Перевага використання a KeyValuePair<TKey,TValue>полягає в тому, що ми можемо дати компілятору більше інформації про те, що є у нашому словнику. Розширити на прикладі Кріса (в якому ми маємо два словники, що містять <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;
}
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)
{
// ...
}