在項(xiàng)目中,在使用哈希表時(shí),有時(shí)會需要Override GetHashCode,
C# GetHashCode 的實(shí)現(xiàn)方式
。這里給出一種普遍的做法:版本1:
實(shí)現(xiàn)一個(gè)helper,傳遞類型T,返回這個(gè)類型的hashcode。函數(shù)邏輯很直接,只是做了null check而已;如果obj不為空,則直接使用obj的hash code。
public class HashHelper{ private int _seed = 17; public int Hash<t>(T obj) { // why 31? // https://computinglife.wordpress.com/2008/11/20/why-do-hash-functions-use-prime-numbers/ // shortly, to reduce the conflict of hashing key's distrabution return 31 * _seed + ((obj == null) ? -1 : obj.GetHashCode()); }}</t>
為什么使用了magic number 31? 使用素?cái)?shù)乘積可以相對增加唯一性,減少哈希鍵值分配時(shí)的沖突;而31則是為了編譯器優(yōu)化的考慮(有效的轉(zhuǎn)換為i<<5-1)。大概搜了一下,這種實(shí)現(xiàn)方式來自JAVA中string 的hash code函數(shù)。這里有詳細(xì)介紹:
https://computinglife.wordpress.com/2008/11/20/why-do-hash-functions-use-prime-numbers/
實(shí)現(xiàn)版本2:
可以擴(kuò)展這個(gè)類成為流暢接口,它可以hash各種類型的,對于值類型來說,重載的意義在于減少裝箱;對于集合或泛型,則為了讓外部調(diào)用更自然,可讀性更強(qiáng),
電腦資料
《C# GetHashCode 的實(shí)現(xiàn)方式》(http://www.shangyepx.com)。
public class HashFluent{ private int _seed = 17; private int _hashContext; public HashFluent Hash<t>(T obj) { // why 31? // https://computinglife.wordpress.com/2008/11/20/why-do-hash-functions-use-prime-numbers/ // shortly, to reduce the conflict of hashing key's distrabution _hashContext = 31 * _seed + ((obj == null) ? -1 : obj.GetHashCode()); return this; } public HashFluent Hash(int? value) { _hashContext = 31 * _seed + ((value == null) ? -1 : value.GetHashCode()); return this; } public HashFluent Hash(IEnumerable sequence) { if (sequence == null) { _hashContext = 31 * _hashContext + -1; } else { foreach (var element in sequence) { _hashContext = 31 * _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 is important}</t>