【问题标题】:KeyValuePair VS DictionaryEntryKeyValuePair VS DictionaryEntry
【发布时间】:2009-05-25 05:20:22
【问题描述】:

泛型KeyValuePair和DictionaryEntry有什么区别?

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

【问题讨论】:

    标签: c#


    【解决方案1】:

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

    【讨论】:

    • 肯定是泛化(limeyfied)或泛化(yankeefied)
    • 您要查找的词是generalized。 ;)
    • "generified" 更多的是 generic 而不是 general
    • 我认为它应该是通用的,但我知道什么? 幽默>
    • 只有我会说通用吗?
    【解决方案2】:

    KeyValuePair 用于遍历 Dictionary 。这是 .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)
    {
      // ...
    }
    

    【讨论】:

    • KeyValuePair 是泛型,另一个是前泛型。建议使用前者。
    • 我想他明白一个是泛型​​的,一个是非泛型的。我认为他的问题是为什么我们都需要?
    • 如果这就是他的要求,那么,我们并不真正需要两者——只是泛型直到 .net 2 才可用,并且为了向后兼容,他们留下了非泛型的东西。有些人可能仍然喜欢使用非通用的东西,但不强烈推荐。
    • 这个答案对我来说更有意义。
    【解决方案3】:

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

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

    列表

    1. 打火机

    2. 在列表中插入更快

    3. 搜索比字典慢

    4. 这可以序列化为 XMLSerializer

    5. 更改键值是不可能的。键值对只能在创建过程中赋值。如果您想更改,请删除并在同一位置添加新项目。

    字典

    1. 插入速度较慢。必须计算Hash

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

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

    4. 您可以更改和更新字典。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-11
      • 1970-01-01
      • 1970-01-01
      • 2014-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多