简体   繁体   English

“具有相同键的项目”例外;枚举键的字典

[英]“Item with same key” exception; dictionary with enum keys

I've got a Dictionary<TKey,TValue> into which I'm inserting a lot of data. 我有一个Dictionary<TKey,TValue> ,我正在插入大量数据。 The keys are an enum. 键是枚举。 I keep getting this exception: 我一直得到这个例外:

An item with the same key has already been added. 已添加具有相同键的项目。

But I don't see any dupes, although I suspect some of my enums have the same value. 但我没有看到任何欺骗,虽然我怀疑我的一些枚举具有相同的价值。 Would that cause a duplicate key error? 这会导致重复键错误吗? I thought an enum was a special type, so it's value wouldn't matter. 我认为枚举是一种特殊的类型,所以它的价值无关紧要。

The exception isn't very helpful...it doesn't tell me which key is tripping the dupe. 例外情况不是很有用......它没有告诉我哪个键绊倒了。 I'm using an initializer list. 我正在使用初始化列表。


Edit: Used some regex magic to convert my initializer list into separate .Add calls. 编辑:使用一些正则表达式魔术将我的初始化列表转换为单独的.Add调用。 Found the key, but I'm still not seeing the dupe... 找到钥匙,但我还没有看到傻瓜......

如果枚举的多个成员具有相同的数字表示形式,则可能是异常的原因。

By default the numeric representation of Enums increment so unless you are specifying duplicate values there shouldn't be any. 默认情况下,枚举的数字表示增加,除非您指定重复值,否则不应该有任何值。

Try running the below replacing by T with your enum and see if any of the values conflict. 尝试运行以下用您的枚举替换T,并查看是否有任何值冲突。

return Enum.GetValues(typeof(T));

If not then the only alternative I see is that you are using an enum as a key twice. 如果没有,那么我看到的唯一选择是你使用枚举作为键两次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM