KeyValuePair VS DictionaryEntry

Jay*_*h.7 110 c#

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)

  • +1为"generified".那是一个字吗?:-P (72认同)
  • 当然它是通用的(limeyfied),或通用的(yankeefied) (25认同)
  • 你要找的单词是_generalized_.;) (6认同)
  • "泛化",如更多*通用*不*一般* (5认同)
  • 当然它是一般化的? (3认同)
  • 我是唯一会说一般的人吗? (2认同)

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)

  • KeyValuePair是Generics,另一个是pre-generics.推荐使用前者. (4认同)
  • 如果这就是他所要求的,那么,我们并不真正需要两者 - 它只是在.net 2之前不能使用泛型,并且他们将非泛型内容留给了后向兼容性.有些人可能仍然喜欢使用非通用的东西,但不强烈推荐. (2认同)

小智 14

问题是这样解释的。请参阅以下链接:

https://www.manojphadnis.net/need-to-know-general-topics/listkeyvaluepair-vs-dictionary

列表<键值对>

  1. 打火机

  2. 在列表中插入速度更快

  3. 搜索比字典慢

  4. 这可以序列化为 XMLSerializer

  5. 无法更改键、值。键值对只能在创建时赋值。如果您想更改,请删除并在同一位置添加新项目。

字典<T 键,T 值>

  1. 重的

  2. 插入速度较慢。必须计算哈希

  3. 由于哈希,搜索速度更快。

  4. 无法序列化。需要自定义代码。

  5. 您可以更改和更新词典。