我想使用自定义泛型类作为字典中的键.我应该如何重写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)
谢谢
平等很简单:测试Value1和Value2平等.
对于哈希码,最简单的方法是使用xor来组合来自Value1和的哈希码Value2.
public override bool Equals(SomeKey<T,V> otherKey)
{
return Value1.Equals(otherKey.Value1) && Value2.Equals(otherKey.Value2);
}
public override int GetHashCode()
{
return Value1.GetHashCode() ^ Value2.GetHashCode();
}
Run Code Online (Sandbox Code Playgroud)
有许多计算哈希码的替代方法.如果性能是瓶颈,那么你应该考虑比xor更适合的东西.
例如,Stack Overflow提供这些链接(以及更多):