gpt4 book ai didi

.NET:Type.GetHashCode 是否保证是唯一的?

转载 作者:行者123 更新时间:2023-12-04 02:54:04 25 4
gpt4 key购买 nike

我有人将 Type.GetHashCode 用作主键。我认为这是一个可怕的想法,但我想知道是否有某种记录在案的特殊情况,说明没有两种类型具有相同的哈希码。

最佳答案

GetHashCode 没有任何保证,只是它可能是随机分布的,而不是唯一的。 Documentation特别提到:

The default implementation of the GetHashCode method does not guarantee unique return values for different objects. Furthermore, the .NET Framework does not guarantee the default implementation of the GetHashCode method, and the value it returns will be the same between different versions of the .NET Framework. Consequently, the default implementation of this method must not be used as a unique object identifier for hashing purposes. ... if two objects do not compare as equal, the GetHashCode methods for the two object do not have to return different values.



鼓励随机分布以避免哈希冲突(慢速字典):

For the best performance, a hash function must generate a random distribution for all input.



持久化 GetHashCode 的结果并基于这个持久化值做出任何决定也是一个非常糟糕的主意。同一个对象可能会在下一次应用程序执行时返回不同的哈希码:

The GetHashCode method for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object's Equals method. Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again.



CLR 本身 changed .NET 1 和 .NET 2 之间的字符串的 GetHashCode 实现,并对 32 位和 64 位版本使用不同的哈希算法。

来自 Guidelines and rules for GetHashCode :

GetHashCode is designed to do only one thing: balance a hash table. Do not use it for anything else.



你应该看看 cryptographic hashes如果您想要基于对象值的几乎唯一的哈希码。

关于.NET:Type.GetHashCode 是否保证是唯一的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7458139/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com