如何为自定义数据结构创建哈希码?

A-T*_*ype 6 c# hash

我已经制作了一个自定义的"Coordinate"数据结构,它根据某个系统定义了一个对象的位置.

坐标定义如下:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,总结一下,它包含一个int Face(0到5),一个int X,int Y和int Shell.X,Y和Shell都在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;
Run Code Online (Sandbox Code Playgroud)

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

对不起,这个问题相当简单,但出于某种原因,我很难过.我只是在寻找有关如何编写此哈希代码的建议,以便它不会发生冲突.

lon*_*ero 12

如果这不是最好的方法,它可以是一个很好的方法:

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

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