C# KeyValuePair VS DictionaryEntry

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/905424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 02:29:48  来源:igfitidea点击:

KeyValuePair VS DictionaryEntry

c#

提问by Jaywith.7

What is the difference between KeyValuePair which is the generic version and DictionaryEntry?

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

Why KeyValuePair is used instead of DictionaryEntry in generic Dictionary class?

为什么在通用 Dictionary 类中使​​用 KeyValuePair 而不是 DictionaryEntry?

回答by Chris

KeyValuePair < T,T > is for iterating through Dictionary < T,T >. This is the .Net 2 (and onwards) way of doing things.

KeyValuePair < T,T > 用于遍历 Dictionary < T,T >。这是 .Net 2(及以后)的做事方式。

DictionaryEntry is for iterating through HashTables. This is the .Net 1 way of doing things.

DictionaryEntry 用于遍历 HashTables。这是 .Net 1 的做事方式。

Here's an example:

下面是一个例子:

Dictionary<string, int> MyDictionary = new Dictionary<string, int>();
foreach (KeyValuePair<string, int> item in MyDictionary)
{
  // ...
}

Hashtable MyHashtable = new Hashtable();
foreach (DictionaryEntry item in MyHashtable)
{
  // ...
}

回答by cdmckay

KeyValuePair<TKey,TValue>is used in place of DictionaryEntrybecause it is generified. The advantage of using a KeyValuePair<TKey,TValue>is that we can give the compiler more information about what is in our dictionary. To expand on Chris' example (in which we have two dictionaries containing <string, int>pairs).

KeyValuePair<TKey,TValue>被用来代替 ofDictionaryEntry因为它是泛型的。使用 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;
}