作为通用版本的KeyValuePair与DictionaryEntry有什么不同?
为什么在泛型字典类中使用KeyValuePair而不是DictionaryEntry?
发布于 2009-05-25 05:46:23
KeyValuePair<TKey,TValue>被用来代替DictionaryEntry,因为它是泛化的。使用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;
}发布于 2009-05-25 05:24:06
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)
{
// ...
}发布于 2021-07-31 07:25:12
这就是这个问题的解释。请参阅以下链接:
https://www.manojphadnis.net/need-to-know-general-topics/listkeyvaluepair-vs-dictionary
List< KeyValuePair >
在List中插入
慢
可以序列化为XMLSerializer的
Dictionary
由于哈希,
无法序列化
https://stackoverflow.com/questions/905424
复制相似问题