微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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/

原文地址:https://www.jb51.cc/csharp/97648.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐