actually "1" is a string, 1.GetHashCode() return 1, "1".GetHashCode() returns 177556 on my machine (.NET 1.0)if you read the documentation for Object.GetHashCode carefully"...
A hash function should be based on an immutable data member. The hash function should return exactly the same value regardless of any changes that are made to the object. Basing the hash function on a mutable data member can cause serious problems, including never being able to access that object in a hash table
..."and ValueType.GetHashCode:
"...
The GetHashCode method applies to types derived from ValueType. One or more fields of the derived type is used to calculate the return value. If one or more of those fields contains a mutable value, the return value might be unpredictable, and unsuitable for use as a key in a hash table.
.."
A hash function should be based on an immutable data member. The hash function should return exactly the same value regardless of any changes that are made to the object. Basing the hash function on a mutable data member can cause serious problems, including never being able to access that object in a hash table
..."and ValueType.GetHashCode:
"...
The GetHashCode method applies to types derived from ValueType. One or more fields of the derived type is used to calculate the return value. If one or more of those fields contains a mutable value, the return value might be unpredictable, and unsuitable for use as a key in a hash table.
.."
值得关注这个问题,希望高手来解答这个问题。
asp.net object的hashcode生成的原理是怎样的?有何意义?
学习一下。
If the class doesn't override Object.GetHashCode and doesn't provide its own implementation, it will inherent Object.GetHashCode.
While Object.GetHashCode only guarantees different value for different object in the whole syste. Two objects with same value will generate different HashCodes even they exist in same process. On the other hand, if the class overrides Object.GetHashCode, it should provide an implementation that depends on the certain member of the object. Whether the HashCode will change for the same object would depend on how the GetHashCode is implemented.
For string class, HashCode is caculated solely from the string value. So it should be the same for the same string on different machine, different time.
但是有可能两个不同的值有相同的GetHashCode的值