.NET:Type.GetHashCode 是否保证唯一?
我有人使用 Type.GetHashCode 就好像它是主键一样。我认为这是一个可怕的想法,但我想知道是否有某种记录的特殊情况表明没有两种类型具有相同的哈希码。
I have someone using Type.GetHashCode as if it were a primary key. I think this is a horrible idea but I wanted to know if there was some sort of documented special case that says no two types would have the same hash code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
GetHashCode 没有任何保证,除了它可能是随机分布,而不是唯一的。 文档特别提到:
鼓励随机分布以避免哈希冲突(慢字典):
保存 GetHashCode 的结果并基于此保存的值做出任何决策也是一个非常糟糕的主意。同一对象可能会在下一次应用程序执行时返回不同的哈希代码:
CLR 本身更改了之间的字符串的 GetHashCode 实现.NET 1 和 .NET 2 并针对 32 位和 64 位版本使用不同的哈希算法。
来自 GetHashCode 指南和规则:
您应该查看 加密哈希(如果您想要基于对象值的几乎唯一的哈希代码)。
There are no guarantees around GetHashCode except that it will likely be randomly distributed, not unique. Documentation specifically mentions that:
Random distribution is encouraged to avoid hash collisions (slow Dictionaries):
It is also a very bad idea to persist results of GetHashCode and base any decisions on this persisted value. The same object may return different hash code on a next application execution:
CLR itself changed GetHashCode implementation for a String between .NET 1 and .NET 2 and uses different hash algorithm for 32 and 64 bit versions.
From Guidelines and rules for GetHashCode:
You should be looking at cryptographic hashes if you want almost unique hashcode based on the object value.
它不保证是唯一的。
如果您的程序集是强命名的,您可以使用完全限定的类型名称作为唯一键来标识
类型
。It's not guaranteed to be unique.
If your assemblies are strongly named you could use the fully qualified type name as a unique key to identify a
Type
.为对象生成哈希码的目标是在给定数据类型的情况下尽可能唯一,以避免表中发生冲突。但是,这绝对不能保证。许多哈希表实现将每个哈希代码桶链接起来(数组列表)以处理冲突。
The goal of producing a hash code for an object is to be as unique as possible given the type of data to avoid collisions in the table. But, it's absolutely not guaranteed. Many hash table implementations chain (an array list) off of each hash code bucket to deal with collisions.