Risposte:
KeyValuePair<TKey,TValue>
viene utilizzato al posto di DictionaryEntry
perché viene generato. Il vantaggio di usare a KeyValuePair<TKey,TValue>
è che possiamo fornire al compilatore maggiori informazioni su ciò che è nel nostro dizionario. Per espandere l'esempio di Chris (in cui abbiamo due dizionari contenenti <string, int>
coppie).
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> è per l'iterazione attraverso Dictionary <T, T>. Questo è il modo .Net 2 (e successivi) di fare le cose.
DictionaryEntry è per l'iterazione attraverso HashTables. Questo è il modo .Net 1 di fare le cose.
Ecco un esempio:
Dictionary<string, int> MyDictionary = new Dictionary<string, int>();
foreach (KeyValuePair<string, int> item in MyDictionary)
{
// ...
}
Hashtable MyHashtable = new Hashtable();
foreach (DictionaryEntry item in MyHashtable)
{
// ...
}