在不同的 .NET Framework 版本、操作系统版本、处理器架构等中,long.GetHashCode()
得出的值是否可靠地相同?
问题基于other questions that mentions different results on different servers .
// Will I be the same everywhere?
var hash = 2170881568869167279.GetHashCode();
奖励:对于 int
和 uint
来说也是如此吗?
最佳答案
根据GetHashCode
的约定,甚至不需要在同一台机器上的两个不同进程中保持相同:
the default implementation of this method must not be used as a unique object identifier for hashing purposes.
对于某些类型,它可能 - 并且可能 - 以始终返回相同哈希码的方式实现,即使在不同的机器上也是如此。但这是您不应该依赖的实现细节 - 它可能会更改,恕不另行通知。
此外,两个不同的对象可以合法地具有相同的哈希码。在使用 long
的示例中,当您为 long.MinValue 中的所有值创建哈希码时,平均每个哈希码都会有
到 long.MaxValue/int.MaxValue
次long.Maxvalue
。
结论:
不,这不是识别对象实例的可靠方法。
处理数字时,您可以简单地使用数字本身或使用真正的哈希算法。
关于.net - 长.GetHashCode跨环境可靠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14277550/