有个实体类。比如
1 public class Customer
2 {
3 public int ID{get;set;}
4
5 public string Name{get;set;}
6 }
2 {
3 public int ID{get;set;}
4
5 public string Name{get;set;}
6 }
在创建多个这样的实体类过程中。我需要判断2个Customer实例的ID属性是否是同一个。
我们可以这样做
if (CustomerA.ID == CustomerB.ID)
或许我们还有其它方法
1 public override int GetHashCode()
2 {
3 return this.ID.GetHashCode();
4 }
5
6 public override bool Equals(object obj)
7 {
8 if (obj == null)
9 {
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
2 {
3 return this.ID.GetHashCode();
4 }
5
6 public override bool Equals(object obj)
7 {
8 if (obj == null)
9 {
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());
}
getHashCode() 取值范围是 int.MinValue ~ int.MaxValue
它的算法将数字左移动16位,再与原来的数字进行异或操作,最后将结果乘以16进制数15051505
public override int GetHashCode()
{
return (number ^ number << 16)* 0x15051505;
}
实际应用中我们还可以用来测试2个对象是否引用一个堆区