c# - 如何为自定义数据结构制作哈希码?

标签 c# hash

我制作了一个自定义的“坐标”数据结构,它根据特定系统定义对象的位置。

坐标定义如下:

public class Coordinate
{
    public int X;
    public int Y;
    private int face;
    public int Face
    {
        get { return face; }
        set
        {
            if (value >= 6 | value < 0)
                throw new Exception("Invalid face number");
            else
                face = value;
        }
    }
    private int shell;
    public int Shell
    {
        get { return shell; }
        set
        {
            if (value < 0)
                throw new Exception("No negative shell value allowed");
            else
                shell = value;
        }
    }

    public Coordinate(int face, int x, int y, int shell)
    {
        this.X = x;
        this.Y = y;
        this.face = face;
        this.shell = shell;
    }

    public static Coordinate operator +(Coordinate a, Coordinate b)
    {
        return new Coordinate(a.Face + b.Face, a.X + b.X, a.Y + b.Y, a.Shell + b.Shell);
    }

    public override bool Equals(object obj)
    {
        Coordinate other = (obj as Coordinate);
        if (other == null)
            return false;
        else
            return (Face == other.Face && Shell == other.Shell && X == other.X && Y == other.Y);
    }
}

或者,总结一下,它包含一个 int Face(0 到 5),一个 int X,一个 int Y,和一个 int Shell。 X、Y 和 Shell 都绑定(bind)在 0(含)以下。

我完全没有哈希码方面的经验。我需要比较它们,看看它们是否相等。我试过这个:

private const int MULTIPLIER = 89;

[...]

int hashCode = 1;
hashCode = MULTIPLIER * hashCode + obj.X.GetHashCode();
hashCode = MULTIPLIER * hashCode + obj.Y.GetHashCode();
hashCode = MULTIPLIER * hashCode + obj.Face.GetHashCode();
hashCode = MULTIPLIER * hashCode + obj.Shell.GetHashCode();
return hashCode;

我在谷歌搜索时发现了一些东西。但是当我尝试用这种方法编译代码时,我很确定它会遇到冲突,因为它永远不会完成构建。可能会陷入各种困惑的循环,认为一堆坐标是相同的或类似的。

很抱歉这个问题相当初级,但出于某种原因我被难住了。我只是在寻找有关如何编写此哈希码以免发生冲突的建议。

最佳答案

如果这不是最好的方法,它可能是一个足够好的方法:

public override int GetHashCode()
{
   return string.Format("{0}-{1}-{2}-{3}", X, Y, Face, Shell).GetHashCode();
}

更新: 看看这篇文章:http://ericlippert.com/2011/02/28/guidelines-and-rules-for-gethashcode/

关于c# - 如何为自定义数据结构制作哈希码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7924892/

相关文章:

ios - 有没有办法通过 Swift 将 Bcrypt 用于 iOS 开发?

c - 如何在 15 和 18 处处理此警告 ."warning: array subscript has type ‘char’ [-Wchar-subscripts]”

hash - 寻找快速散列功能

ruby - 通过根据项目的属性对对象数组进行分组来构建哈希

c# - 上传 excel 文件时访问路径被拒绝

c# - 在 ELMAH 获取异常之前捕获异常并清除它

c# - Wpf/WinRT点画心

c# - 通过 NuGet 管理器安装 EntityFramework

c# - 如何在 GridView 中的 ListViewItemPresenter 中更改 SelectedBackground

java - 在 Java 中为 XML 生成 SHA-256 哈希