[英]ArgumentException not found in Dictionary ContainsKey check
I have code like this: 我有这样的代码:
if (!likeDict.ContainsKey(s))
{
likeDict.Add(s, s);
}
And I keep getting an error that an item with the same key has already been added. 而且我不断收到一个错误消息,即已添加具有相同密钥的项目。 I thought ContainsKey is the check for this and that is where the error is occuriing, not at the add line.
我以为ContainsKey是对此的检查,这就是发生错误的地方,而不是添加行。 Am I misinterpreting ContainsKey?
我误解了ContainsKey吗?
It sounds like you are using the dictionary in a multithreaded scenario. 听起来您好像在多线程方案中使用字典。 If this is the case, you can switch to using
ConcurrentDictionary<TKey, TValue>
which provides the following TryAdd
method: 在这种情况下,可以切换到使用
ConcurrentDictionary<TKey, TValue>
,它提供以下TryAdd
方法:
bool added = likeDict.TryAdd(s, s);
If you are using this dictionary as a cache for equivalent objects, you could also use the GetOrAdd
method: 如果您将此字典用作等效对象的缓存,则还可以使用
GetOrAdd
方法:
var value = likeDict.GetOrAdd(s, s);
bool added = object.ReferenceEquals(value, s);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.