开发者

How to use a custom generic type as a key in a Dictionary?

I want to use a custom generic class as a key in a dictionary. Ho开发者_JAVA技巧w should I override Equals and GetHashCode?

Eg,

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?
    }
}

Thanks


Equality is simple: test for Value1 and Value2 being equal.

For the hash code the simplest approach is to use xor to combine the hash codes from Value1 and 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();
}

There are lots of alternative ways of calculating the hash code. If performance is a bottleneck then you should consider something more tailored than xor.

For example, Stack Overflow offers these links (and many more):

  • Custom type GetHashCode
  • What is the best algorithm for an overridden System.Object.GetHashCode?


You should override it in a way that GetHashcode reliably returns the same value for the same object, and Equals to always return true for the same objects. The msdn has some advices for implementing GetHashcode (the remarks section).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜