Why won't a Hashtable return true for “ContainsKey” for a key of type byte[] in C#?

前端 未结 4 1422
一个人的身影
一个人的身影 2021-01-22 13:13

Consider the following code:

byte[] bytes = new byte[] { 1, 2, 5, 0, 6 };
byte[] another = new byte[] { 1, 2, 5, 0, 6 };

Hashtable ht = new Hashtable();
ht.Add(         


        
4条回答
  •  梦毁少年i
    2021-01-22 13:39

    It returns false because the hashes don't match. If GetHashCode() doesn't produce a repeatable hash for the same value it won't work in a dictionary.

    byte[] bytes = new byte[] { 1, 2, 5, 0, 6 };
    byte[] another = new byte[] { 1, 2, 5, 0, 6 };
    
    string astring = "A string...";
    string bstring = "A string...";
    
    MessageBox.Show(bytes.GetHashCode() + " " + another.GetHashCode() + " | " + astring.GetHashCode() + " " + bstring.GetHashCode());
    

提交回复
热议问题