KeyValuePair VS DictionaryEntry

Posted 楊柳

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了KeyValuePair VS DictionaryEntry相关的知识,希望对你有一定的参考价值。

There are some difference between KeyValuePair which is the generic version and DictionaryEntry which is non generic version. 

  1. KeyValuePair < T,T > is for iterating through Dictionary < T,T >. This is the .Net 2 way of doing things.
  2. DictionaryEntry is for iterating through HashTables. This is the .Net 1 way of doing things.
  3. KeyValuePair<TKey,TValue> is used in place of DictionaryEntry because it is generic.
The advantage of using a KeyValuePair<TKey,TValue> is that we can give the compiler more information about what is in our dictionary. Esp. the data type
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 VS DictionaryEntry的主要内容,如果未能解决你的问题,请参考以下文章

将字典转换为 List<KeyValuePair>

Hashtable、Dictionary 和 KeyValuePair 有啥区别?

使用KeyValuePair迭代C#字典

KeyValuePair的使用

从 IEnumerable<KeyValuePair<>> 重新创建字典

在 LINQ 查询中将 KeyValuePair 转换为匿名类型