我对不可变类型的 HashCode 有一些疑问。
- 我可以在构造函数中“预先”生成不可变类型的 HashCode 还是有任何理由不这样做?
- 当调用 GetHashCode() 方法时,我是否应该始终再次生成哈希码?
这是一个示例类:
public class Id {
private readonly object _value;
private readonly int _hash = -1;
public Id( object value ) {
_value = value;
_hash = ( int ) ( 7 * value.GetType().GetHashCode() + 7 + 7 * _value.GetHashCode() );
}
public object Value {
get {
return _value;
}
}
public override int GetHashCode() {
return _hash;
}
public override bool Equals( object obj ) {
Id other = obj as Id;
if ( other == null ) {
return false;
}
return this.GetHashCode() == other.GetHashCode();
}
}
最佳答案
您可以预先生成哈希码,但为什么呢?只需在需要时生成它(在 GetHashCode
中)然后可能存储它 - 大多数对象从来不需要具有哈希,因此它只会减慢程序。
Should i always generate the Hashcode again, when the method GetHashCode() is called?
不可变对象(immutable对象)的哈希码应该始终相同,因此无论您是再次生成它还是存储它,它都不会产生任何影响,除非存储会提高性能。
注意:您不应通过比较 HashCode 来定义 Equals
- 两个不同的对象可能具有相同的 HashCode(哈希碰撞)。
关于c# - 在不可变类型的构造函数中生成 HashCode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/910149/