KeyValuePair VS DictionaryEntry


116

通用版本的KeyValuePair与DictionaryEntry有什么区别?

为什么在通用Dictionary类中使用KeyValuePair代替DictionaryEntry?

Answers:


108

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;
}

4
当然可以概括吗?
danielcooperxyz

26
当然是通用的(限制)或通用的(扬克式)
jenson-button-event

7
您要查找的单词是通用的。;)
Jason

5
“泛化”为更通用而不是通用的
TheGeekZn 2015年

2
我是唯一会说普通药的人吗?
Mauro Sampietro

51

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)
{
  // ...
}

4
KeyValuePair是泛型,另一个是前泛型。建议前者使用前者。
纪州

1
我认为他了解一种是泛型的,一种是非泛型的。我认为他的问题是我们为什么同时需要两者?
cdmckay,2009年

3
如果那是他要的,那么,我们确实并不需要两者-只是泛型直到.net 2才可用,并且它们将非泛型的东西留在了向后兼容中。某些人可能仍喜欢使用非通用的东西,但不建议这样做。
克里斯(Chris)2009年

这个答案对我来说更有意义。
美林纳卡米
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.