[英]C# Dictionary ContainsKey/TryGetValue not working
I've looked around for a while and seen plenty of references to modifying GetHashCode()
and things when playing with ContainsKey()
and TryGetValue()
- but all those issues and examples have all been with some obscure user-specific key. 我已经浏览了一段时间,并且在使用
ContainsKey()
和TryGetValue()
时看到了大量有关修改GetHashCode()
和其他内容的引用 - 但所有这些问题和示例都使用了一些模糊的用户特定键。
I have a basic Dictionary<long, object>
. 我有一个基本的
Dictionary<long, object>
。 When trying either ContainsKey()
or TryGetValue()
, it doesn't always get a hit (when it should) and moves on to attempting to populate the missing entry (as it technically should if that were the case). 当尝试
ContainsKey()
或TryGetValue()
,它并不总是得到命中(当它应该)并继续尝试填充缺失的条目(因为在技术上应该如果是这种情况)。
You guessed it: it then complains about the existing key because, well, it exists. 你猜对了:它然后抱怨现有的密钥,因为它存在。
So why is it having problems matching a basic long
key and how do you make it behave? 那么为什么匹配基本的
long
键有问题呢?你如何使它表现出来?
Edit: Code. 编辑:代码。 I have tried several things.
我尝试过几件事。 In their most basic form:
以他们最基本的形式:
public void Add(long id)
{
if (AreaDataDict.ContainsKey(id)) return;
AreaData ad = new AreaData(id);
ad.Load();
AreaDataDict.Add(id, ad);
}
Also: 也:
public void Add(long id)
{
AreaData areaData;
if (AreaDataDict.TryGetValue(id, out areaData)) return;
AreaData ad = new AreaData(id);
ad.Load();
AreaDataDict.Add(id, ad);
}
Edit 2: No key changes are happening. 编辑2:没有发生任何密钥更改。 Other than adding if the value is not found, data is only read from this.
除了添加未找到值之外,仅从中读取数据。
使用ConcurrentDictionary
是答案,幸好受到用户454076的启发。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.