我有一个字典,其中键是 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 answer 的解决方案
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());
最佳答案
向字典提供您自己的 IEqualityComparer
,因为它不知道如何比较 XYZ
类(严格来说,它通过引用比较它们):
class XYZEqualityComparer : IEqualityComparer<XYZ>
{
public bool Equals(XYZ a, XYZ b)
{
return a.X == b.X && a.Y == b.Y && a.Z == b.Z;
}
public int GetHashCode(XYZ x)
{
int hash = x.X ^ x.Y ^ x.Z;
return hash .GetHashCode();
}
}
然后:
Dictionary<XYZ, bool> prevPnts = new Dictionary<XYZ, bool>(new XYZEqualityComparer());
注意:我对 GetHashCode
的实现只是示范性的。阅读What is the best algorithm for an overridden System.Object.GetHashCode?寻找更好的选择。
关于c# - 字典说键不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21245144/