【发布时间】: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<T>吗?如果没有,ContainsKey可能正在尝试通过反射生成哈希码。 -
@AustinDrenski:如果
GetHashCode()已被覆盖,则不会。但实际上,我们需要看到minimal reproducible example...(我们甚至不知道NodePair是结构还是类...)
标签: c# dictionary key