在c#中散列数组

c z*_*c z 15 .net c# arrays hash

简短的问题

如何实现GetHashCode一个Array.

细节

我有一个覆盖的对象Equals,检查:

this.array[n] == otherObject.array[n]
Run Code Online (Sandbox Code Playgroud)

所有narray.

当然,我应该实施补充GetHashCode.我想知道是否有.NET方法可以做到这一点,或者我是否应该实现自己的方式

hash = hash ^ array[n]
Run Code Online (Sandbox Code Playgroud)

澄清

我的对象包含一个数组,我对GetHashCode感兴趣的数组元素.我的数组等价代码仅作为示例 - 就像我的问题所说,但也许我不清楚,我对GetHashCode(不是Equals)感兴趣.我说我自然应该实现补充,GetHashCode因为一旦Equals被覆盖(为了Dictionary正常运行等),实现这一点是.NET的要求.谢谢.

Mic*_*Liu 10

要使用数组元素计算哈希代码,可以将数组转换为IStructuralEquatable,然后调用GetHashCode(IEqualityComparer)方法,为数组中的元素类型传递比较器.

(转换是必要的,因为Array类显式实现了该方法.)

例如,如果您的对象有一个int数组,那么您可以像这样实现GetHashCode:

public override int GetHashCode()
{
    return ((IStructuralEquatable)this.array).GetHashCode(EqualityComparer<int>.Default);
}
Run Code Online (Sandbox Code Playgroud)

如果你很好奇,这里是Array类如何实现GetHashCode方法(来自Reference Source):

internal static int CombineHashCodes(int h1, int h2) {
    return (((h1 << 5) + h1) ^ h2);
}

int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
    if (comparer == null)
        throw new ArgumentNullException("comparer");
    Contract.EndContractBlock();

    int ret = 0;

    for (int i = (this.Length >= 8 ? this.Length - 8 : 0); i < this.Length; i++) {
        ret = CombineHashCodes(ret, comparer.GetHashCode(GetValue(i)));
    }

    return ret;
}
Run Code Online (Sandbox Code Playgroud)

如您所见,当前实现仅使用数组的最后八个元素.