【问题标题】:ContainsKey return unexpected result C# this is super strange needs adviceContainsKey return unexpected result C# 这太奇怪了 需要建议
【发布时间】:2017-10-08 12:59:40
【问题描述】:

我有一个

Dictionary<NodePair, string> repo;

我已经实现了

GetHashCode(), Equals()

关于

NodePair

当我尝试使用

搜索密钥时
if(Repo.ContainsKey(new NodePair(OneTree.Root, AnotherTree.Root)))

但是,当我这样做时,它会返回 false

foreach (NodePair pair in Repo.Keys)
   if (pair.Equals(new NodePair(OneTree.Root, AnotherTree.Root)))
        Console.WriteLine();

调试器停在

Console.WriteLine()

当我这样做时发生了同样的事情

foreach (NodePair pair in Repo.Keys)
   if (pair.GetHashCode() == (new NodePair(OneTree.Root, AnotherTree.Root)).GetHashCode())
        Console.WriteLine();

那么为什么 ContainsKey() 返回 false?????????

编辑把所有东西放在一起:

 foreach (NodePair pair in Repo.Keys)
    if (pair.Equals(new NodePair(OneTree.Root, AnotherTree.Root)))
         Console.WriteLine();

 foreach (NodePair pair in Repo.Keys)
    if (pair.GetHashCode() == (new NodePair(OneTree.Root, AnotherTree.Root)).GetHashCode())
         Console.WriteLine();

 if (Repo.ContainsKey(new NodePair(OneTree.Root, AnotherTree.Root)))
      Console.WriteLine();

前两个Console.WriteLine() 命中,最后一个没有。谁能解释一下?

【问题讨论】:

  • 请完整显示minimal reproducible example(尤其是Equals、GetHashCode,以及您如何填写字典)。很可能您的类型是可变的,并且您使用相同的键填写了字典。
  • 旁注:显然您确实知道如何查看 Microsoft Reference Source 中 ContainsKey 的来源,因此您可能需要 edit 标题来阐明您正在寻找什么类型的帮助.
  • @AlexeiLevenkov,如果我用相同的键填写字典,那么它不包含键()?
  • 你在NodePair上实现IEquatable&lt;T&gt;吗?如果没有,ContainsKey 可能正在尝试通过反射生成哈希码。
  • @AustinDrenski:如果GetHashCode() 已被覆盖,则不会。但实际上,我们需要看到minimal reproducible example...(我们甚至不知道NodePair 是结构还是类...)

标签: c# dictionary key


【解决方案1】:

它的实现如下:

private int FindEntry(TKey key)
{
    if (key == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
    }

    if (buckets != null)
    {
        int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
        for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next)
        {
            if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) return i;
        }
    }
    return -1;
}

如果需要,您可以查看Dictionary 的完整源代码,因为它可以在线获得。如需调试,请查看how to debug .NET code

【讨论】:

猜你喜欢
  • 2016-07-12
  • 1970-01-01
  • 2019-02-14
  • 2022-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多