重囗另类BBWSeⅹHD,av狼论坛,精品一卡2卡三卡4卡乱码理论,体育生gv老师浪小辉3p警察

C# GetHashCode 的實現方式 -電腦資料

電腦資料 時間:2019-01-01 我要投稿
【www.ipr-jzsc.com - 電腦資料】

    在項目中,在使用哈希表時,有時會需要Override GetHashCode,

C# GetHashCode 的實現方式

。這里給出一種普遍的做法:

    版本1:

    實現一個helper,傳遞類型T,返回這個類型的hashcode。函數邏輯很直接,只是做了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? 使用素數乘積可以相對增加唯一性,減少哈希鍵值分配時的沖突;而31則是為了編譯器優化的考慮(有效的轉換為i<<5-1)。大概搜了一下,這種實現方式來自JAVA中string 的hash code函數。這里有詳細介紹:

    https://computinglife.wordpress.com/2008/11/20/why-do-hash-functions-use-prime-numbers/

    實現版本2:

    可以擴展這個類成為流暢接口,它可以hash各種類型的,對于值類型來說,重載的意義在于減少裝箱;對于集合或泛型,則為了讓外部調用更自然,可讀性更強,

電腦資料

C# GetHashCode 的實現方式》(http://www.ipr-jzsc.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>

最新文章
主站蜘蛛池模板: 富源县| 东平县| 通州区| 方山县| 怀集县| 钟山县| 望奎县| 洪江市| 西安市| 逊克县| 洛南县| 台东市| 阿坝县| 夏河县| 南投县| 曲阳县| 鄂尔多斯市| 莒南县| 阳新县| 木里| 佛教| 平舆县| 宝丰县| 平顶山市| 宜川县| 沙田区| 华亭县| 林芝县| 凤冈县| 新建县| 西安市| 南召县| 浦江县| 高青县| 兴城市| 香河县| 景泰县| 酉阳| 绥阳县| 宜兴市| 甘孜|