问题
Possible Duplicate:
How do I create a HashCode in .net (c#) for a string that is safe to store in a database?
I use C# 4.0 and gets the string hash by invoking:
"my string".GetHashCode()
Code generated by this call is stored into database to future use. This hash code is used to find some subset of strings and then to equal comparison.
Questions are:
- Is it a standardized hash calculation? May I assume that it is possible to calculate the same hash in different environments like C# in .Net 3.0 or future .Net editions?
- Is it possible to calculate the same hash function on yourself by writing it in Java, PL/SQL, Ruby, etc?
- Can I assume that hash generated today will be the same tomorrow in the same environment? For example when I shutdown my computer and run the program again, or change locale, or some other settings?
- What are the limits of portability?
- I know I can do it yourself, but maybe some kind of portability is provided?
回答1:
From MSDN:
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.
So no, you cannot assume that the value produced by GetHashCode
is stable. This isn't just theoretical, either - we've seen the value change in the past.
If you want a stable hash, you'll have to generate it yourself.
回答2:
Rule: Consumers of GetHashCode cannot rely upon it being stable over time or across appdomains.
回答3:
http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx
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.
回答4:
No. It is not portable. You should never use this method for anything other than balancing a hash tree. it's implementation has changed between versions of the Framework, and behaves differently for 32-bit / 64-bit CLR.
Eric Lippert has a blog post on rules and proper uses for this function.
Instead, you should be using SHA1Managed for inserting a hash into the database.
来源:https://stackoverflow.com/questions/8029529/is-the-net-string-hash-function-portable