基本上,到目前为止我有以下内容:
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
。这是个坏主意吗?如果是,应该怎么做?