C# GetHashCode 的实现方式


在项目中,在使用哈希表时,有时会需要Override 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());
	}
}



为什么使用了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各种类型的,对于值类型来说,重载的意义在于减少装箱;对于集合或泛型,则为了让外部调用更自然,可读性更强。




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
}


  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值