基本的に、私はこれまでのところ以下を持っています:
class Foo {
public override bool Equals(object obj)
{
Foo d = obj as Foo ;
if (d == null)
return false;
return this.Equals(d);
}
#region IEquatable<Foo> Members
public bool Equals(Foo other)
{
if (this.Guid != String.Empty && this.Guid == other.Guid)
return true;
else if (this.Guid != String.Empty || other.Guid != String.Empty)
return false;
if (this.Title == other.Title &&
this.PublishDate == other.PublishDate &&
this.Description == other.Description)
return true;
return false;
}
}
したがって、問題は次のとおりですGuid
。一意の識別子である必須ではないフィールドがあります。これが設定されていない場合は、2 つのオブジェクトが等しいかどうかを判断する試みとして、精度の低いメトリックに基づいて等しいかどうかを判断する必要があります。これはうまくいきますが、GetHashCode()
面倒になります...どうすればいいですか?単純な実装は次のようになります。
public override int GetHashCode() {
if (this.Guid != String.Empty)
return this.Guid.GetHashCode();
int hash = 37;
hash = hash * 23 + this.Title.GetHashCode();
hash = hash * 23 + this.PublishDate.GetHashCode();
hash = hash * 23 + this.Description.GetHashCode();
return hash;
}
しかし、2 種類のハッシュが衝突する可能性はどのくらいでしょうか? 確かに、そうなるとは思いません1 in 2 ** 32
。これは悪い考えですか? もしそうなら、どうすればいいですか?