Antworten:
KeyValuePair<TKey,TValue>wird anstelle von verwendet, DictionaryEntryweil es generiert wird. Der Vorteil der Verwendung von a KeyValuePair<TKey,TValue>besteht darin, dass wir dem Compiler mehr Informationen darüber geben können, was sich in unserem Wörterbuch befindet. Um das Beispiel von Chris zu erweitern (in dem wir zwei Wörterbücher haben, die <string, int>Paare enthalten ).
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> dient zum Durchlaufen des Wörterbuchs <T, T>. Dies ist die .Net 2-Methode (und höher).
DictionaryEntry dient zum Durchlaufen von HashTables. Dies ist die .Net 1-Methode.
Hier ist ein Beispiel:
Dictionary<string, int> MyDictionary = new Dictionary<string, int>();
foreach (KeyValuePair<string, int> item in MyDictionary)
{
// ...
}
Hashtable MyHashtable = new Hashtable();
foreach (DictionaryEntry item in MyHashtable)
{
// ...
}