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?
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.
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.
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
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