关于GetHashCode()方法
MSDN文档对GetHashCode的解释是:如果相同类型的两个对象表示同一个值,散列函数就必须为这两个对象返回相同的常量值(一个整数)。
程序每次运行时,对象的散列值都不同,但相同的对象每次运行时的散列值都保持相互一致。
例如:
Person p1 = new Person("wd", 23);
Person p2 = new Person("wd", 23);
Person p3 = p2;
this.Label1.Text = p1.GetHashCode() + " - " + p2.GetHashCode() + " - " + p3.GetHashCode();
Person p2 = new Person("wd", 23);
Person p3 = p2;
this.Label1.Text = p1.GetHashCode() + " - " + p2.GetHashCode() + " - " + p3.GetHashCode();
运行结果:
第一次运行结果:15572461 - 34491160 - 34491160
第二次运行结果:64788746 - 39092916 - 39092916
int i1 = 2;
int i2 = 2;
int i3 = 98;
int i2 = 2;
int i3 = 98;
第一次运行结果:2 - 2 - 98
第二次运行结果:2 - 2 - 98
string s1 = "hello";
string s2 = "hello";
string s3 = "world";
this.Label1.Text = s1.GetHashCode() + "<br />" + s2.GetHashCode() + "<br />" + s3.GetHashCode();
string s2 = "hello";
string s3 = "world";
this.Label1.Text = s1.GetHashCode() + "<br />" + s2.GetHashCode() + "<br />" + s3.GetHashCode();
第一次运行结果:
-695839
-695839
-1506749525
-695839
-1506749525
第二次运行结果:
-695839
-695839
-1506749525
-695839
-1506749525
本贴子以“现状”提供且没有任何担保,同时也没有授予任何权利
This posting is provided "AS IS" with no warranties, and confers no rights.
This posting is provided "AS IS" with no warranties, and confers no rights.
浙公网安备 33010602011771号