Ответы:
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)
{
// ...
}