如果我有一个 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
使用私有(private)方法显式实现了 IDictionary
。
我的问题:为什么 ConcurrentDictionary
是这样实现的?隐藏已实现接口(interface)的使用有什么好处?
最佳答案
My question: Why is ConcurrentDictionary implemented like that?
我相信这是为了鼓励您考虑并发的含义 - 多个线程可能同时写入相同的 key 。因此,添加现有 key 不太可能是编程错误,应谨慎考虑。
- 如果要无条件覆盖,使用索引器
- 如果要添加或更新,其中更新可以使用现有值,使用
AddOrUpdate
- 如果您希望尽可能添加,但不覆盖任何现有值,请使用
TryAdd
如果您发现自己经常需要现有的 Add
行为,您总是可以编写自己的扩展方法。
关于c# - 为什么我需要从 ConcurrentDictionary 转换为 Dictionary 才能使用 Add()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21847703/