.GetHashCode 是否保证跨系统/平台版本相同?
如果我在两个系统/框架版本中使用 Object.GetHashCode()
方法,是否可以保证相同的输入获得相同的值?换句话说,它的值是否成为持久数据的良好密钥?
注意:我不关心这个问题中的碰撞。
作为奖励,我能保证在 Mono 与 Microsoft .Net 中获得相同的价值吗?
Possible Duplicate:
Can I depend on the values of GetHashCode() to be consistent?
If I use the Object.GetHashCode()
method across two systems/framework versions, am I guaranteed to get the same value for the same input? In other words, does its value make a good key for persistent data?
Note: I don't care about collisions in this problem.
As a bonus, am I guaranteed to get the same value in Mono vs. Microsoft .Net?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
没有。还有其他问题吗? :-)
使用的算法未发布,也不在 Ecma 标准中。
我将引用MSDN String.GetHashCode (我认为这个例子已经足够好了)
No. Other questions? :-)
The algorithms used aren't published nor they are in the Ecma standard.
I'll quote from the MSDN String.GetHashCode (I think that this example is good enough)
从技术上讲,这取决于您的类如何重写
GetHashCode
。如果你有这个:那么这在 Mono 和 .NET 中是一致的。 :)
当然,如果您的
GetHashCode
实现依赖于不保证跨平台一致性的类型(例如string
),则MyClass.GetHashCode()
也将不一致。Technically, it depends on how your classes override
GetHashCode
. If you have this:then that would be consistent in Mono and .NET. :)
Of course if your
GetHashCode
implementation depends on types that do not guarantee consistency across platforms (e.g.string
), thenMyClass.GetHashCode()
will also not be consistent.答案是否定的
规则:GetHashCode 的使用者不能依赖它随着时间的推移或跨应用程序域的稳定
假设您有一个 Customer 对象,其中包含一堆字段,例如名称、地址等。如果您在两个不同的进程中创建具有完全相同数据的两个此类对象,则它们不必返回相同的哈希码。如果您在星期二在一个进程中创建这样的对象,将其关闭,然后在星期三再次运行该程序,则哈希码可能会不同。/blockquote>
阅读GetHashCode 指南和规则的完整文章
The answer is No
Rule: Consumers of GetHashCode cannot rely upon it being stable over time or across appdomains
Suppose you have a Customer object that has a bunch of fields like Name, Address, and so on. If you make two such objects with exactly the same data in two different processes, they do not have to return the same hash code. If you make such an object on Tuesday in one process, shut it down, and run the program again on Wednesday, the hash codes can be different./blockquote>
Read full article from Guidelines and rules for GetHashCode
如果您重写 GetHashCode() 并提供您自己的实现,则可以返回相同的结果。尽管我不确定为什么您希望使用该返回值作为持久存储的密钥,但当您的对象首次插入存储库时,为它们提供自己的预定(计算)密钥也同样容易。恕我直言,但是使用返回的哈希码作为密钥似乎您为了自己的利益而试图变得太聪明。
You could make return the same thing if you override
GetHashCode()
and provide your own implementation. Although I'm unsure why you would want to use the return from that as a key to persistent storage, it is just as easy to give your objects their own predetermined (calculated) key when they are first inserted into the repository. All due respect, but using the returned hash code as the key just seems like you are trying to be too clever for your own good.