ハッシュ値を組み合わせる

2020/09/16
C#
hash

C#でふたつ以上のハッシュ値を組み合わせて使う方法。

System.HashCode.Combine

.NET Standard2.1以降なら、System.HashCode.Combine[1]を使う

public override int GetHashCode()
{
    return HashCode.Combine(value1, value2);
}

HashCode.Combineは8個まで引数を取れるオーバーロードがある。

tupleを使う

C#7以降なら言語機能としてtupleが使える。

public override int GetHashCode()
{
    return (value1, value2, value3).GetHashCode();
}

tupleにはGetHashCodeが定義されている。
同様に匿名型も使えるがタプルは値型でGCのお世話にならない分高速。

自力で組み合わせる

古いUnityなど、.NET Standard2.1以前なら自力で書く必要がある場合がある。

public override int GetHashCode()
{
    //  1117 と 1777 は共に素数
    const int Prime1 = 1117;
    const int Prime2 = 1777;

    int hash = Prime1;
    unchecked
    {
        hash = hash * Prime2 + value1.GetHashCode();
        hash = hash * Prime2 + value2.GetHashCode();
        hash = hash * Prime2 + value3.GetHashCode();
        //  ...
    }
    return hash;
}

Prime1Prime2は互いに別の素数であればよいが、ある程度大きい値であるべき。(本当か?)
uncheckedは明示的にオーバーフローを許容するキーワード。

© 2019-2022 hassakulab.com, built with Gatsby