在.NET GetHashCode方法中,很多地方都使用.NET 方法.特别是在快速查找集合中的项目或确定相等性时.是否有关于如何GetHashCode为我的自定义类实现覆盖的标准算法/最佳实践,因此我不会降低性能?
像许多人一样,我使用ReSharper来加速开发过程.当您使用它来覆盖类的相等成员时,它为GetHashCode()生成的代码生成如下所示:
public override int GetHashCode()
{
unchecked
{
int result = (Key != null ? Key.GetHashCode() : 0);
result = (result * 397) ^ (EditableProperty != null ? EditableProperty.GetHashCode() : 0);
result = (result * 397) ^ ObjectId;
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
当然我有一些自己的成员,但我想知道的是为什么397?
我想使用自定义泛型类作为字典中的键.我应该如何重写Equals和GetHashCode?
例如,
public class SomeKey<T,V>
{
public T Value1 { get; set; }
public V Value2 { get; set; }
public SomeKey(T val1, V val2)
{
this.Value1 = val1;
this.Value2 = val2;
}
public override bool Equals(SomeKey<T,V> otherKey)
{
//whats the best option here?
}
public override int GetHashCode()
{
//whats the best option here?
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢