如何在Hashtable上覆盖GetHashCode?

时间:2018-05-04 10:22:06

标签: c# hashtable gethashcode

我想覆盖C#中哈希表的GetHashCode方法。

我将哈希表用作复杂对象中的多维键。

怎么可能呢?

hKey中不同的密钥顺序必须返回相同的hashCode

这样的事情不起作用:

Hashtable hkey; 

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

return i;

2 个答案:

答案 0 :(得分:0)

如果你扩展它,你可以覆盖Hashtable的GetHashCode():

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

常数来自这个答案:https://stackoverflow.com/a/34006336/8006950

有关散列的更多信息:http://www.eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx

答案 1 :(得分:0)

好的,这项工作很好,多亏了所有

    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;
    }
相关问题