我有一个字典,其中键是Autodesk API的XYZ对象,值是布尔值。我试图检查字典中是否存在一个键。
我的问题:如果字典包含键new XYZ(1,1,1),并且我使用myDictionary.ContainsKey(new XYZ(1,1,1))检查字典是否包含此键,则始终返回false。
为什么会这样发生,我该怎么办?我认为类XYZ需要实现它的Equals方法,但正如我之前提到的,我没有创建这个类,它是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());