如何在C#结构中实现GetHashCode()

编程入门 行业动态 更新时间:2024-10-23 07:31:44
本文介绍了如何在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()

本文发布于:2023-11-06 06:52:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562989.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:结构   如何在   GetHashCode

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!