In a project, when using a hash table, the override GetHashCode is sometimes required. Here is a common practice:
Version 1:
Implement a helper that passes the type T, returning this type of hashcode. The function logic is straightforward, just a null check, and if obj is not null, use the hash code of obj directly.
public class Hashhelper{private int _seed = 17;public int hash<t> (T obj) {//Why 31?//http://www.php.cn///shortly, To reduce the conflict of hashing key ' s Distrabutionreturn * _seed + ((obj = = null)? -1:obj. GetHashCode ());}}
Why was magic number 31 used? The multiplication of prime numbers can be relatively unique, reducing the conflict of hash key value allocations, while 31 is for compiler optimizations (valid conversions to i<<5-1). Probably a bit, this implementation comes from the hash code function of string in Java. Here is a detailed description:
https://computinglife.wordpress.com/2008/11/20/why-do-hash-functions-use-prime-numbers/
Implementation Version 2:
This class can be extended to become fluent interface, it can hash various types, for value types, the meaning of overloading is to reduce boxing, for the collection or generic, in order to make external calls more natural, more readable.
public class Hashfluent{private int _seed = 17;private int _hashcontext;public hashfluent hash<t> (T obj) {//why 31?/ /http://www.php.cn///shortly, to reduce the conflict of hashing key ' s Distrabution_hashcontext = * _seed + ((obj = = n ull)? -1:obj. GetHashCode ()); return this;} Public hashfluent Hash (int? value) {_hashcontext = + * _seed + ((value = = null)? -1:value. GetHashCode ()); return this;} Public hashfluent Hash (IEnumerable sequence) {if (sequence = = null) {_hashcontext = $ * _hashcontext +-1;} Else{foreach (var element in sequence) {_hashcontext = * _hashcontext + (element = = null)? -1:element. GetHashCode ());}} return this;} public override int GetHashCode () {return _hashcontext;} Add more overridings here. Add value types overridings to avoid boxing which are important}
The above is the implementation of C # GetHashCode content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!