【发布时间】:2018-07-09 16:29:36
【问题描述】:
我一直在寻找一个错误,我有一本字典坚持说一个键不存在,尽管它的比较器实际上说它存在。比如下面的sn-p,就抛出了异常:
if (!dictionary.ContainsKey(key))
{
var comparer = dictionary.Comparer;
foreach (var _key in dictionary.Keys)
{
if (comparer.Equals(key, _key) &&
comparer.Equals(_key, key) &&
comparer.GetHashCode(key) == comparer.GetHashCode(_key) &&
comparer.GetHashCode(_key) == comparer.GetHashCode(key))
{
throw new Exception("Key exists, but dictionary doesn't find it");
}
}
}
字典是一个通用的Dictionary<TKey, TValue>,带有默认的相等比较器(空构造函数)。 TKey 类实现了正确的 GetHashCode 和 Equals 方法。
这里有什么我可能遗漏的吗?我完全不知所措!
【问题讨论】:
-
添加到字典后哈希码有变化吗?
-
key 属于哪一种?
-
像往常一样,minimal reproducible example 会暴露问题...stackoverflow.com/questions/3007296/… 可能被认为是重复的。
标签: c# .net dictionary equality