基本上,到目前为止,我有以下内容:
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
,它是一个唯一标识符。如果没有设置,那么我需要尝试根据不太准确的指标来确定相等性,以尝试确定两个对象是否相等。这工作正常,但它使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;
}
但是这两种类型的哈希冲突的可能性有多大?当然,我不希望它是1 in 2 ** 32
。这是一个坏主意,如果是这样,我应该怎么做?