c# - 字典说键不存在

标签 c# autodesk

我有一个字典,其中键是 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/

相关文章:

c# - 通过C#读取SQL Server中存储过程设置的值

c# - C# 中如何存在全局函数?

c# - 如何检查 datagridview 中的选定行是否为空(没有项目)C#

autocad - 在accoreconsole.exe中加载自定义.net dll

javascript - Autodesk Forge-集成基于属性的选择/隔离

3d - 物体的精确边界框

javascript - 关于 extract.autodesk.io 的问题 - 采用文件路径而不是使用文件选择器进行选择

c# - 解析没有 :Split 的日志字符串

c# - 如何获取控件的屏幕截图? DrawToBitmap 不工作

c# - 一个过程中的不同版本的企业库