0

クラスのハッシュコードを生成するとき、そのクラスのメンバーのハッシュコードを使用してもよいですか? サンプルクラスは次のとおりです。

class Sample
{
    private readonly string _strA, _strB;
    public Sample(string strA, string strB)
    {
        this._strA = strA;
        this._strB = strB;
    }
    public override int GetHashCode()
    {
        return (this._strA + "###" + this._strB).GetHashCode();
    }
}

_strA にも _strB にも文字列 "###" が含まれていない限り、これは機能すると思います。ただし、文字列でハッシュコードがどのように生成されるかの詳細がわからないため、完全にはわかりません。

「目的に合わせて調整できる2 つの数値のハッシュコードを作成する」の投稿で解決策を見ましたが、私の解決策はもっと単純だと思います (どちらの文字列にも "###" が含まれていない限り)。

4

2 に答える 2

2

オブジェクトの全体的なハッシュ コードに寄与する複数のフィールドがある場合、シンプルでかなり効果的なアプローチは次のとおりです。

public override int GetHashCode()
{
    int hash = 17;

    hash = hash*23 + field1.GetHashCode();
    hash = hash*23 + field2.GetHashCode();
    hash = hash*23 + field3.GetHashCode();

    // And so on for all applicable fields.
    // field1, field2 and field3 are all class field members.

    return hash;
}
于 2012-07-31T15:30:15.410 に答える
1

Times 33 hash のようなものを使用して、ハッシュ コードを数学的に結合することをお勧めします。現在のコードでは、呼び出されるたびに一時的な文字列を作成しているため、GetHashCodeパフォーマンスが低下する可能性があります。

public override int GetHashCode()
{
    // omit null-coalesce if we know them to be non-null
    return (33 * (this._strA ?? "").GetHashCode())
         + (this._strB ?? "").GetHashCode();
}

クラスが真に不変である場合、前もってハッシュコードを計算すると、4 バイトの価値がある場合があります。

private readonly int _hash;

public Sample(string strA, string strB)
{
    this._strA = strA;
    this._strB = strB;
    this._hash = (33 * (this._strA ?? "").GetHashCode())
               + (this._strB ?? "").GetHashCode();
}

public override int GetHashCode()
{
    return this._hash;
}
于 2012-07-31T15:21:02.067 に答える