KeyValuePair(通用版本)和DictionaryEntry有什么区别?
为什么在通用的Dictionary类中使用KeyValuePair而不是DictionaryEntry?
cdm*_*kay 102
KeyValuePair<TKey,TValue>
用来代替DictionaryEntry
它,因为它是普遍的.使用a的优点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;
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*ris 45
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)
{
// ...
}
Run Code Online (Sandbox Code Playgroud)
小智 14
问题是这样解释的。请参阅以下链接:
https://www.manojphadnis.net/need-to-know-general-topics/listkeyvaluepair-vs-dictionary
列表<键值对>
打火机
在列表中插入速度更快
搜索比字典慢
这可以序列化为 XMLSerializer
无法更改键、值。键值对只能在创建时赋值。如果您想更改,请删除并在同一位置添加新项目。
字典<T 键,T 值>
重的
插入速度较慢。必须计算哈希
由于哈希,搜索速度更快。
无法序列化。需要自定义代码。
您可以更改和更新词典。
归档时间: |
|
查看次数: |
78426 次 |
最近记录: |