GetHashCode() 的研究

有个实体类。比如

1 public class Customer
2 {
3     public int ID{get;set;}
4     
5     public string Name{get;set;}
6 }

在创建多个这样的实体类过程中。我需要判断2个Customer实例的ID属性是否是同一个。

 

我们可以这样做

  if (CustomerA.ID == CustomerB.ID)

或许我们还有其它方法

        public override int GetHashCode()
        {
            return this.ID.GetHashCode();
        }

        public override bool Equals(object obj)
        {
            if (obj == null)
            {
10                 return false;
11             }
12
13             if (obj.GetType() == this.GetType())
14             {
15                 return obj.GetHashCode() == this.GetHashCode();
16             }
17
18             return false;
19         }
20

那么我们就可以这样判断了

if (CustomerA.Equals(CustomerB))

以下是我对GetHashCode()做的一个简单测试

public static void RunSnippet()
{
    int aaa= 111;
    Console.WriteLine(aaa.GetHashCode());
    int bbb= 111;   
    Console.WriteLine(bbb.GetHashCode());
    string xxx="111";
    Console.WriteLine(xxx.GetHashCode());
    string yyy ="111";
    Console.WriteLine(yyy.GetHashCode());
    string zzz ="zzz";
    Console.WriteLine(zzz.GetHashCode());
}

image

getHashCode() 取值范围是 int.MinValue ~ int.MaxValue

它的算法将数字左移动16位,再与原来的数字进行异或操作,最后将结果乘以16进制数15051505

public override int GetHashCode()

{

  return (number ^ number << 16)* 0x15051505;

}

实际应用中我们还可以用来测试2个对象是否引用一个堆区 

原文地址:https://www.cnblogs.com/yuanhuaming/p/1621780.html