gpt4 book ai didi

c# - 遍历字典时出现 KeyNotFoundException

转载 作者:太空宇宙 更新时间:2023-11-03 13:25:20 28 4
gpt4 key购买 nike

我有一段看似简单的代码,它一直在抛出我不希望发生的错误:

// Private member
private Dictionary<InputField, bool> m_Completed;

// Later on, during some method
foreach (InputField filter in this.m_Completed.Keys)
if (this.m_Completed[filter])
completedCount += 1;

我得到的错误:

KeyNotFoundException: The given key was not present in the dictionary

这是来自循环中的“if”语句。

对我来说,这意味着迭代器已经与字典的实际键失去同步。这可能吗?没有线程正在进行。

我的工作流程有问题吗?我可以想出一些其他方法来获取我的计数,但我仍然想知道为什么我的代码会抛出错误。

最佳答案

InputField 或其基类之一以某种方式实现 GetHashCode,以便在实例的生命周期内不会返回相同的值。

这完全破坏了 DictionaryHashSet 的功能,它们依赖于一致的哈希码。

因此,一个可能的解决方案是让您的 InputField 覆盖 GetHashCodeEquals。如果它已经覆盖了这些,您将需要修复实现。

您会在 Eric Lippert 的博客文章 Guidelines and rules for GetHashCode 上找到用于证明正确实现的很棒指南。 .

在这种情况下,这是当前实现中似乎缺少的指南:

Guideline: the integer returned by GetHashCode should never change

Ideally, the hash code of a mutable object should be computed from only fields which cannot mutate, and therefore the hash value of an object is the same for its entire lifetime.

关于c# - 遍历字典时出现 KeyNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22610292/

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