编程语言
首页 > 编程语言> > c# – 使用字符串属性计算类的哈希码的最佳方法是什么?

c# – 使用字符串属性计算类的哈希码的最佳方法是什么?

作者:互联网

参见英文答案 > Best hashing algorithm in terms of hash collisions and performance for strings                                    9个
我有一个字符串属性的类,我需要覆盖GetHashCode()方法.

class A
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
    public string Prop3 { get; set; }
}

第一个想法是做这样的事情:

public override int GetHashCode()
{
    return Prop1.GetHashCode() ^ Prop2.GetHashCode() ^ Prop3.GetHashCode();
}

第二个想法是:

public override int GetHashCode()
{
    return String.Join(";", new[] {Prop1, Prop2, Prop3}).GetHashCode();
}

什么是最好的方法?

解决方法:

你不应该只是将它们混合在一起,因为这不考虑订购.想象一下,你有两个对象:

"foo", "bar", "baz"

"bar", "foo", "baz"

使用简单的XOR,这两者都具有相同的散列.幸运的是,它很容易解决.这是我用来组合哈希的代码:

static int MultiHash(IEnumerable<object> items)
{
    Contract.Requires(items != null);

    int h = 0;

    foreach (object item in items)
    {
         h = Combine(h, item != null ? item.GetHashCode() : 0);
    }

    return h;
}

static int Combine(int x, int y)
{
    unchecked
    {
         // This isn't a particularly strong way to combine hashes, but it's
         // cheap, respects ordering, and should work for the majority of cases.
         return (x << 5) + 3 + x ^ y;
    }
}

有很多方法可以组合哈希,但通常会像这样非常简单.如果由于某种原因它不适用于您的情况,MurmurHash具有非常强大的哈希组合,您可以拉.

标签:c,gethashcode
来源: https://codeday.me/bug/20190613/1231006.html