【问题标题】:Why do I need to cast from ConcurrentDictionary to IDictionary in order to use Add()?为什么我需要从 ConcurrentDictionary 转换为 Dictionary 才能使用 Add()?
【发布时间】:2014-03-17 20:21:33
【问题描述】:

如果我有一个ConcurrentDictionary 并想使用Add() 函数,我需要转换为IDictionary

var cd = new ConcurrentDictionary<int, int>();
cd.Add(1, 1);  // Compile error: does not contain a definition for 'Add'
IDictionary<int, int> id = cd;
id.Add(1, 1);  // Works

问题ConcurrentDictionary and IDictionary 告诉我这是因为ConcurrentDictionary 使用私有方法显式实现了IDictionary

我的问题:为什么ConcurrentDictionary 是这样实现的?隐藏已实现接口的使用有什么好处?

【问题讨论】:

    标签: c# concurrency concurrentdictionary


    【解决方案1】:

    我的问题:为什么要这样实现 ConcurrentDictionary?

    我相信这是为了鼓励您考虑并发含义 - 多个线程可能同时写入相同的键。因此,添加现有密钥不太可能是编程错误,应谨慎考虑。

    • 如果要无条件覆盖,请使用索引器
    • 如果要添加或更新,在更新可以使用现有值的地方,使用AddOrUpdate
    • 如果您想在可能的情况下添加,但不覆盖任何现有值,请使用TryAdd

    如果您发现自己经常需要现有的Add 行为,您可以随时编写自己的扩展方法。

    【讨论】:

    • 这也可能是因为IDictionary.Add 被简单地实现为if (!TryAdd(...)) throw ...;,这非常简单,即使在那些对并发字典有意义的情况下,调用者仍然可以选择完全执行同样的事情,无需通过IDictionary 访问字典。
    【解决方案2】:

    我认为您可以尝试使用 ConcurrentDictionay 中的 TryAdd() 或 AddOrUpdate() 方法,如您在此处所见。

    http://msdn.microsoft.com/es-es/library/dd287191(v=vs.110).aspx

    【讨论】:

      猜你喜欢
      • 2011-05-18
      • 2013-10-02
      • 1970-01-01
      • 1970-01-01
      • 2016-12-12
      • 1970-01-01
      • 2019-02-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多