我找到了一个 GetHashCode() 的实现,看起来像这样
Guid _hashCode = Guid.NewGuid();
public override int GetHashCode()
{
return _hashCode.GetHashCode();
}
即使认为 Equals 看起来是正确的,但说此实现会导致许多关于 .NET 的假设被打破是否正确?
public override bool Equals(object obj)
{
if (obj.GetType() != trustedEntity.GetType())
return false;
TrustedEntity typedObj = (TrustedEntity)obj;
if (trustedEntity.BackTrustLink != typedObj.BackTrustLink)
return false;
if (trustedEntity.ForwardTrustLink != typedObj.ForwardTrustLink)
return false;
if (trustedEntity.EntryName != typedObj.EntryName)
return false;
return true;
}
我听到的反驳论点是,GetHashCode 需要在对象创建后永远不会更改。这是因为此对象存储在字典中。
有人可以为我解决这个问题,并解释如果对象发生变化,GetHashCode 需要发生什么,这最终会改变 Equals 方法吗?
最佳答案
From MSDN (Notes to Implementers section) :
A hash function must have the following properties:
If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two object do not have to return different values.
The GetHashCode method for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object's Equals method. Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again.
For the best performance, a hash function must generate a random distribution for all input.
根据此对象的 Equals
方法,您可能也违反了文档中的第一点。
关于c# - 覆盖 GetHashCode() 时使用 Guid().GetHashCode() 有什么缺点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12943590/