Answers:
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>用于遍历Dictionary <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)
{
// ...
}