How to implement GetHashCode() in a C# struct

This question already has an answer here:

  • What is the best algorithm for an overridden System.Object.GetHashCode? 17 answers

  • 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.

    链接地址: http://www.djcxy.com/p/39772.html

    上一篇: 为什么GetHashCode方法需要在C#中进行移位

    下一篇: 如何在C#结构中实现GetHashCode()