我經常會自我壓倒Equals()
和GetHashCode()
來實現具有相同屬性值的業務對象相同的語義。這導致代碼是重複的寫和脆弱的維持(屬性,都會添加一個/不更新這兩個覆蓋的)。在C#中簡化覆蓋Equals(),GetHashCode()以實現更好的可維護性
的代碼最終看起來像這樣(在實施意見,歡迎):
public override bool Equals(object obj)
{
if (object.ReferenceEquals(this, obj)) return true;
MyDerived other = obj as MyDerived;
if (other == null) return false;
bool baseEquals = base.Equals((MyBase)other);
return (baseEquals &&
this.MyIntProp == other.MyIntProp &&
this.MyStringProp == other.MyStringProp &&
this.MyCollectionProp.IsEquivalentTo(other.MyCollectionProp) && // See http://stackoverflow.com/a/9658866/141172
this.MyContainedClass.Equals(other.MyContainedClass));
}
public override int GetHashCode()
{
int hashOfMyCollectionProp = 0;
// http://computinglife.wordpress.com/2008/11/20/why-do-hash-functions-use-prime-numbers/
// BUT... is it worth the extra math given that elem.GetHashCode() should be well-distributed?
int bitSpreader = 31;
foreach (var elem in MyCollectionProp)
{
hashOfMyCollectionProp = spreader * elem.GetHashCode();
bitSpreader *= 31;
}
return base.GetHashCode()^//^is a good combiner IF the combined values are well distributed
MyIntProp.GetHashCode()^
(MyStringProp == null ? 0 : MyStringProp.GetHashValue())^
(MyContainedClass == null ? 0 : MyContainedClass.GetHashValue())^
hashOfMyCollectionProp;
}
我的問題
- 是實現模式的聲音?
- 是^充分考慮到有助於元件值均勻分佈?我需要通過31對的-N組合賦予其散列集合元素時分佈均勻繁殖?
- 看來這代碼可以被抽象成代碼,使用反射來確定公共屬性,建立的是,手工編碼的溶液相匹配的表達式樹,並根據需要執行表達式樹。這種方法看起來是否合理?有沒有現有的實現?
爲什麼downvote(超過一年發佈之後)?這個問題是非常合法的。如果有什麼問題,請說出來。 – 2013-05-30 17:38:40