我有一本字典,其中键是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());