【发布时间】:2014-09-10 00:39:50
【问题描述】:
这是在 C# 中。我有一个问题,即 Dictionary.ContainsKey 会返回 false,即使我知道密钥在其中。
很遗憾,我没有任何代码可显示。代码不容易拼凑起来;它分布在多个类中,并通过事件等触发。我编写的快速单元测试没有重现问题。
这是调试会话期间即时窗口的输出(添加了 cmets 并进行了更改以保护细节):
// throws KeyNotFoundException
myDict[key]
// throws KeyNotFoundException
myDict[new MyKey("SomeString .1", "SomeOtherString", SomeEnum.Foo)]
// Element [5] is the key
myDict.Keys
Count = 10
[0]: {...}
[1]: {...}
[2]: {...}
[3]: {...}
[4]: {...}
[5]: {Foo SomeOtherString SomeString .1}
[6]: {...}
[7]: {...}
[8]: {...}
[9]: {...}
// Get key at element [5]
enumerator.Current
{Foo SomeOtherString SomeString .1}
[My.Namespace.KeyType]: {Foo SomeOtherString SomeString .1}
SomeEnum: Foo
SomeOtherStringProperty: "SomeOtherString"
// key used to do lookup
key
{Foo SomeOtherString SomeString .1}
[My.Namespace.KeyType]: {Foo SomeOtherString SomeString .1}
SomeEnum: Foo
SomeOtherStringProperty: "SomeOtherString"
// hash codes of key in dictionary matches hash code of lookup key
enumerator.Current.GetHashCode()
193014103
key.GetHashCode()
193014103
一些额外说明:
- 用作键的类型已覆盖 GetHashCode 和 等于。
- 字典构造为 new Dictionary() 没有额外的构造函数参数。
- 通过调试,我已经验证了 键类型中的GetHashCode被调用,而不是Equals(obj)
- 当 应用程序运行时,只加载了一个具有密钥类型的 DLL, 所以在不同版本的情况下可能不是同一类型的情况 同一个DLL
有谁知道为什么会发生这种情况?
感谢您的帮助 - 我的想法已经用完了。
【问题讨论】:
标签: c# dictionary keynotfoundexception