簡體   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