哈希代码是一个用于在相等测试过程中标识对象的数值。 它还可以作为一个集合中的对象的索引。
Equals()用以決定2個object是否相同,DataGrid一類控制項會使用,多數DataGrid的選擇列問題都出於這裏
GetHashCode()和Equals()是一對的,定義為:"若2個object的GetHashCode()返回值不相同:以Equals()為準,該2個object一定是不同的object"
總之,繼承MasterBase時要清楚一個問題:何謂不同的object?
public static bool operator ==(MasterBase a, MasterBase b) {
if (Object.ReferenceEquals(a, b)) {
return true;
}
if (!Object.ReferenceEquals(a, null) && !Object.ReferenceEquals(b, null)
&& a.GetType() == b.GetType()
&& a.CompanyCode == b.CompanyCode && a.Code == b.Code) {
return true;
}
return false;
}
public static bool operator !=(MasterBase a, MasterBase b) {
return !(a == b);
}
public override int GetHashCode() {
return
(this.CompanyCode == null ? 0 : this.CompanyCode.GetHashCode()) * 17 +
(this.Code == null ? 0 : this.Code.GetHashCode());
}
public override bool Equals(object obj) {
return this == obj as MasterBase;
}
参考:http://blog.youkuaiyun.com/wyfde123/article/details/6397130