How to implement GetHashCode() in a C# struct [duplicate]

白昼怎懂夜的黑 提交于 2019-12-12 00:54:20

问题


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

My struct:

  private struct Key
  {
    ...

    public override int GetHashCode()
    {
      return ?;
    }

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

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

a)

    return FolderID ^ SubItemKind.GetHashCode() ^ SubItemID;

or b)

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

回答1:


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());

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



来源:https://stackoverflow.com/questions/32502181/how-to-implement-gethashcode-in-a-c-sharp-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!