私は自分自身をオーバーライドEquals()
しGetHashCode()
、同一のプロパティ値を持つビジネス オブジェクトが等しいというセマンティックを実装することがよくあります。これにより、コードの記述が反復的になり、保守が脆弱になります (プロパティが追加され、オーバーライドの 1 つまたは両方が更新されません)。
コードは次のようになります (実装に関するコメントは大歓迎です)。
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 を乗算する必要がありますか?
- このコードは、リフレクションを使用してパブリック プロパティを決定し、ハンド コーディングされたソリューションと一致する式ツリーを構築し、必要に応じて式ツリーを実行するコードに抽象化できるようです。そのアプローチは合理的に見えますか?どこかに既存の実装はありますか?