繁体   English   中英

如何在哈希表上覆盖GetHashCode?

[英]How to override GetHashCode on a Hashtable?

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

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

那怎么办呢?

hKey不同顺序的Key必须返回相同的hashCode

像这样的东西不起作用:

Hashtable hkey; 

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

return i;

如果这样扩展哈希表,则可以覆盖它的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

好的,这项工作很好,谢谢大家

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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