【发布时间】:2014-02-10 06:44:02
【问题描述】:
我有一个字典,其中键是 XYZ 对象,值是 boolean。 XYZ 类来自 Autodesks API,所以它不是我创建的类。我正在尝试检查字典中是否存在键。
我的问题:如果字典包含键 new XYZ(1,1,1) 并且我使用 myDictionary.ContainsKey(new XYZ(1,1,1) 检查字典是否包含此键总是返回 false。
为什么会发生这种情况,我该如何解决?我认为XYZ 类需要实现其Equals 方法,但正如我之前提到的,我没有创建这个类,它是Autodesks API 的一部分。还是我做错了什么?
Dictionary<XYZ, bool> prevPnts = new Dictionary<XYZ, bool>();
prevPnts[new XYZ(1,1,1)] = true;
// Always says the pnt doesnt exist?
if (prevPnts.ContainsKey(new XYZ(1,1,1)))
TaskDialog.Show("Contains");
else TaskDialog.Show("NOT Contains");
使用 Konrads 答案的解决方案
class XYZEqualityComparer : IEqualityComparer<XYZ>
{
public bool Equals(XYZ a, XYZ b)
{
if (Math.Abs(a.DistanceTo(b)) <= 0.05)
return true;
return false;
}
public int GetHashCode(XYZ x)
{
int hash = 17;
hash = hash * 23 + x.X.GetHashCode();
hash = hash * 23 + x.Y.GetHashCode();
hash = hash * 23 + x.Z.GetHashCode();
return hash;
}
}
Dictionary<XYZ, bool> prevPnts = new Dictionary<XYZ, bool>(new XYZEqualityComparer());
【问题讨论】: