本文介绍了如何在C#结构中实现GetHashCode()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个重写 Equals()方法的结构,编译器抱怨 GetHashCode()没有被重写.

I have a struct that overrides the Equals() method and the compiler complains about GetHashCode() not being overridden.

我的结构:

  private struct Key
  {
    ...

    public override int GetHashCode()
    {
      return ?;
    }

    public int FolderID;
    public MyEnum SubItemKind;
    public int SubItemID;
  }

实现 GetHashCode()方法的正确方法是什么?

What is the right way to implement the GetHashCode() method?

a)

    return FolderID ^ SubItemKind.GetHashCode() ^ SubItemID;

或b)

    return FolderID.GetHashCode() ^ SubItemKind.GetHashCode() ^ SubItemID.GetHashCode();

推荐答案

始终是后者.前者是不够的,因为大多数位是0(您的数字很可能很小),而那些零是最高有效位.您会浪费大量的哈希码,从而导致更多的冲突.

Always the latter. The former isn't sufficient because most bits are 0 (your numbers are most likely small), and those zeroes are in the most significant bits. You'd be wasting a lot of the hash code, thus getting a lot more collisions.

另一种常见的处理方式是将每个项目乘以质数并依靠溢出:

Another common way of doing it is to multiply each item by a prime number and relying on overflows:

return unchecked(FolderID.GetHashCode() * 23 * 23
                 + SubItemKind.GetHashCode() * 23
                 + SubItemID.GetHashCode());

已更新,以根据stakx的注释使用 unchecked 显式支持溢出.

Updated to use unchecked for explicit overflow support as per stakx's comment.

这篇关于如何在C#结构中实现GetHashCode()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 11:36