gpt4 book ai didi

c# - Dictionary.GetKey 返回 False,即使 key 存在 - GetHashCode/Equals 已经被覆盖

转载 作者:行者123 更新时间:2023-11-30 15:28:31 25 4
gpt4 key购买 nike

这是在 C# 中。我有一个问题,即 Dictionary.ContainsKey 返回 false,即使我知道其中的键。

不幸的是,我没有任何代码可以显示。代码不容易拼凑起来;它分布在多个类中,并通过事件等触发。我编写的快速单元测试没有重现问题。

这是调试 session 期间即时窗口的输出(添加注释并更改以保护细节):

// 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)
  • 当应用程序运行时,只有一个具有 key 类型的 DLL 被加载,所以它可能不是不同版本的同一类型的情况同一个动态链接库

有谁知道为什么会发生这种情况?

感谢您的帮助 - 我的想法已经用完了。

最佳答案

The type used as the key has overridden methods for GetHashCode and Equals.

这是我要检查的第一件事。如果哈希码基于可变值,则肯定会导致此问题。

来自 MSDN :

In general, for mutable reference types, you should override GetHashCode only if:

  • You can compute the hash code from fields that are not mutable; or

  • You can ensure that the hash code of a mutable object does not change while the object is contained in a collection that relies on its hash code.

Otherwise, you might think that the mutable object is lost in the hash table. If you do choose to override GetHashCode for a mutable reference type, your documentation should make it clear that users of your type should not modify object values while the object is stored in a hash table.

关于c# - Dictionary.GetKey 返回 False,即使 key 存在 - GetHashCode/Equals 已经被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25755642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com