gpt4 book ai didi

c# - 我应该如何实现 Object.GetHashCode() 以实现复杂的相等性?

转载 作者:太空狗 更新时间:2023-10-29 20:06:34 25 4
gpt4 key购买 nike

到目前为止,基本上我有以下内容:

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。这是个坏主意吗?如果是,我应该怎么做?

最佳答案

一个非常简单的hash code method for custom classes是将每个字段的哈希码按位异或在一起。它可以像这样简单:

int hash = 0;
hash ^= this.Title.GetHashCode();
hash ^= this.PublishDate.GetHashCode();
hash ^= this.Description.GetHashCode();
return hash;

来自link above :

XOR has the following nice properties:

  • It does not depend on order of computation.
  • It does not “waste” bits. If you change even one bit in one of the components, the final value will change.
  • It is quick, a single cycle on even the most primitive computer.
  • It preserves uniform distribution. If the two pieces you combine are uniformly distributed so will the combination be. In other words, it does not tend to collapse the range of the digest into a narrower band.

如果您希望字段中有重复值,则 XOR 效果不佳,因为重复值在进行 XOR 运算时会相互抵消。由于您将三个不相关的字段散列在一起,在这种情况下这应该不是问题。

关于c# - 我应该如何实现 Object.GetHashCode() 以实现复杂的相等性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1072058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com