【发布时间】:2009-05-25 05:20:22
【问题描述】:
泛型KeyValuePair和DictionaryEntry有什么区别?
为什么在泛型 Dictionary 类中使用 KeyValuePair 而不是 DictionaryEntry?
【问题讨论】:
标签: c#
泛型KeyValuePair和DictionaryEntry有什么区别?
为什么在泛型 Dictionary 类中使用 KeyValuePair 而不是 DictionaryEntry?
【问题讨论】:
标签: c#
KeyValuePair<TKey,TValue> 用于代替DictionaryEntry,因为它是泛型的。使用KeyValuePair<TKey,TValue> 的好处是我们可以为编译器提供更多关于我们字典中内容的信息。扩展 Chris 的示例(其中我们有两个包含 <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 用于遍历 Dictionary 。这是 .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)
{
// ...
}
【讨论】:
这就是问题的解释方式。请参阅以下链接:
https://www.manojphadnis.net/need-to-know-general-topics/listkeyvaluepair-vs-dictionary
列表
打火机
在列表中插入更快
搜索比字典慢
这可以序列化为 XMLSerializer
更改键值是不可能的。键值对只能在创建过程中赋值。如果您想更改,请删除并在同一位置添加新项目。
字典
重
插入速度较慢。必须计算Hash
由于哈希,搜索速度更快。
无法序列化。需要自定义代码。
您可以更改和更新字典。
【讨论】: