Three Principles of gehashcode:
1. If two objects are equal (defined by operator =), they must generate the same hash code. Otherwise, the hash code cannot be used to search for objects in the container.
2. For any object A, A. gethashcode () must be an instance variant (invariant ). That is, no matter what method is called on A, A. gethashcode () must always return the same
. This ensures that the objects in the "hash bucket" are always in the correct "hash bucket.
3. For all input, the hash function should generate a random distribution among all integers. In this way, we can improve the efficiency from a hash container.
Object. gethashcode satisfies principles 1 and 2, and is used in a hash table (hashtable, dictionary ).
Valuetype. gethashcode is not 100% compliant with Principle 1, principle 2, and Principle 3. problems may occur when using a hash table (hashtable, dictionary ).
Test environment. Net framwwork2.0 (no sp patch is installed), vs2005
Proof:
1. If two value-type entities have both value-type fields and reference type fields, and the gethashcode of the first field is equal, the hash codes of the two entities are equal.
2. If two value-type entities have only one field and the gethashcode of the character is the same, the hash codes of the two entities are the same.
3. If all two value-type entities only contain integer, floating-point, or enumeration fields (excluding decimal, bool, and custom structure types) and all fields have the same gethashcode
The two entities have the same hash code.
4. If both value-type entities only contain reference type fields and the gethashcode of the first field is the same, the hash codes of the two entities are the same.
conclusion:
assume there is a struct structtest
structtest has two instances, S1, s2
1. when a structtest contains multiple fields, each field is an integer (except char), float type, or enumeration. If and only when the gethashcode of each field in S1 and S2 is the same, s1.gethashcode is equal to s2.gethashcode
2. otherwise, if the gethashcode of the first field of S1 and S2 is the same, s1.gethashcode is equal to s2.gethashcode