C#HashCode Builder [英] C# HashCode Builder

查看:109
本文介绍了C#HashCode Builder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我过去经常使用apache哈希码构建器

I used to use the apache hashcode builder a lot

C#是否存在这样做

推荐答案

这是我的自制建筑商。

用法:

hash = new HashCodeBuilder().
             Add(a).
             Add(b).
             Add(c).
             Add(d).
             GetHashCode();

什么类型字段无关紧要 a b c d 易于扩展,无需创建数组。

It does not matter what type fields a,b,c and d are, easy to extend, no need to create array.

资料来源:

public sealed class HashCodeBuilder
{
    private int hash = 17;

    public HashCodeBuilder Add(int value)
    {
        unchecked
        {
            hash = hash * 31 + value; //see Effective Java for reasoning
             // can be any prime but hash * 31 can be opimised by VM to hash << 5 - hash
        }
        return this;
    }

    public HashCodeBuilder Add(object value)
    {
        return Add(value != null ? value.GetHashCode() : 0);
    }

    public HashCodeBuilder Add(float value)
    {
        return Add(value.GetHashCode());
    }

    public HashCodeBuilder Add(double value)
    {
        return Add(value.GetHashCode());
    }

    public override int GetHashCode()
    {
        return hash;
    }
}

样本用法:

public sealed class Point
{
    private readonly int _x;
    private readonly int _y;
    private readonly int _hash;

    public Point(int x, int y)
    {
        _x = x;
        _y = y;
        _hash = new HashCodeBuilder().
            Add(_x).
            Add(_y).
            GetHashCode();
    }

    public int X
    {
        get { return _x; }
    }

    public int Y
    {
        get { return _y; }
    }

    public override bool Equals(object obj)
    {
        return Equals(obj as Point);
    }

    public bool Equals(Point other)
    {
        if (other == null) return false;
        return (other._x == _x) && (other._y == _y);
    }

    public override int GetHashCode()
    {
        return _hash;
    }
}

这篇关于C#HashCode Builder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆