简体   繁体   中英

How to override GetHashCode on a Hashtable?

I would like override the GetHashCode method on a hashtable in C#.

I use the hashtable as a multidimensional key in a complex object.

How could do that ?

Different order of Keys in hKey must return the same hashCode .

Something like this doesn't work:

Hashtable hkey; 

int i = 0;
foreach (DictionaryEntry de in hkey)
    i ^= de.GetHashCode();

return i;

You can override GetHashCode() of a Hashtable if you extend it as such:

public class MyHashtable : Hashtable
{
    public override int GetHashCode()
    {
        const int seed = 1009;
        const int factor = 9176;

        var hash = seed;
        foreach (var key in Keys)
        {
            hash = hash * factor + key.GetHashCode();
        }

        return hash;
    }
}

Constants were taken from this answer: https://stackoverflow.com/a/34006336/8006950

More on hashing: http://www.eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx

Ok this work fine , thanks to all

    static void Main(string[] args)
    {
        Hashtable h = new Hashtable()
        {
          { "string1", 1 },
          { "string2", 2 }
        };

        int i = GetHashCode(h);

        h = new Hashtable()
        {
          { "string2", 2},
          { "string1", 1 }
        };

        int j = GetHashCode(h);

        Debug.Assert(i == j);

        h = new Hashtable()
        {
          { "string1", 1 },
          { "string2", 2 }
        };

        i = GetHashCode(h);

        h = new Hashtable()
        {
          { "string2", 3},
          { "string1", 1 }
        };

        j = GetHashCode(h);

        Debug.Assert(i != j);
    }

    static int GetHashCode(Hashtable ht)
    {
        if (ht.Count == 0) return ht.GetHashCode();

        int h = 0;
        foreach(DictionaryEntry de in ht)
        {
            h ^= new { de.Key, de.Value }.GetHashCode();
        }
        return h;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM