这是在C#中的问题。我的问题是,即使我知道键存在,Dictionary.ContainsKey返回false。
很不幸,我没有任何代码可展示。这段代码不容易整合在一起;它分散在多个类中,并通过事件等方式触发。我编写的一个快速单元测试无法复现这个问题。
以下是调试会话期间立即窗口的输出(添加了注释并更改以保护细节):
很不幸,我没有任何代码可展示。这段代码不容易整合在一起;它分散在多个类中,并通过事件等方式触发。我编写的一个快速单元测试无法复现这个问题。
以下是调试会话期间立即窗口的输出(添加了注释并更改以保护细节):
// 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 和 Equals 方法。
- 使用 new Dictionary() 构造字典时没有传递额外的构造参数。
- 通过调试,我已经验证了键类型中的 GetHashCode 被调用了,但没有调用 Equals(obj)。
- 当应用程序运行时,只有一个加载了具有键类型的 DLL,因此这可能不是同一 DLL 的不同版本的情况。
有人知道为什么会发生这种情况吗?
感谢任何帮助-我已经没有更多的想法了。