Is .GetHashCode guaranteed to be the same across systems/platform versions? [duplicate]

荒凉一梦 提交于 2019-12-04 06:26:53

问题


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?


回答1:


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)

The behavior of GetHashCode is dependent on its implementation, which might change from one version of the common language runtime to another. A reason why this might happen is to improve the performance of GetHashCode.




回答2:


Technically, it depends on how your classes override GetHashCode. If you have this:

class MyClass
{
    public override int GetHashCode() { return 42; }
}

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), then MyClass.GetHashCode() will also not be consistent.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/7859359/is-gethashcode-guaranteed-to-be-the-same-across-systems-platform-versions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!