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

我已经制作了一个自定义的“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);
    }
}

或者,总结一下,它包含一个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;

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

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

解决方法

如果这不是最好的方法,它可以是一个很好的方法
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/

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...