Réponses:
KeyValuePair<TKey,TValue>est utilisé à la place de DictionaryEntryparce qu'il est généré. L'avantage d'utiliser a KeyValuePair<TKey,TValue>est que nous pouvons donner au compilateur plus d'informations sur le contenu de notre dictionnaire. Pour développer l'exemple de Chris (dans lequel nous avons deux dictionnaires contenant des <string, int>paires).
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> est pour itérer dans Dictionary <T, T>. C'est la façon de faire .Net 2 (et au-delà).
DictionaryEntry sert à parcourir les HashTables. C'est la façon de faire .Net 1.
Voici un exemple:
Dictionary<string, int> MyDictionary = new Dictionary<string, int>();
foreach (KeyValuePair<string, int> item in MyDictionary)
{
// ...
}
Hashtable MyHashtable = new Hashtable();
foreach (DictionaryEntry item in MyHashtable)
{
// ...
}