加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:08:04 所属栏目:百科 来源:网络整理
导读:我已经制作了一个自定义的“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)
我已经制作了一个自定义的“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/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读