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

前端 未结 4 1450
一个人的身影
一个人的身影 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条回答
  •  独厮守ぢ
    2021-01-22 13:48

    Here's a sample implementation:

      class Program {
        static void Main(string[] args) {
          byte[] bytes = new byte[] { 1, 2, 5, 0, 6 };
          byte[] another = new byte[] { 1, 2, 5, 0, 6 };
    
          Hashtable ht = new Hashtable(new ByteArrayComparer());
          ht.Add(bytes, "hi");
          System.Diagnostics.Debug.Assert(ht.ContainsKey(another));
        }
    
        private class ByteArrayComparer : IEqualityComparer {
          public int GetHashCode(object obj) {
            byte[] arr = obj as byte[];
            int hash = 0;
            foreach (byte b in arr) hash ^= b;
            return hash;
          }
          public new bool Equals(object x, object y) {
            byte[] arr1 = x as byte[];
            byte[] arr2 = y as byte[];
            if (arr1.Length != arr2.Length) return false;
            for (int ix = 0; ix < arr1.Length; ++ix)
              if (arr1[ix] != arr2[ix]) return false;
            return true;
          }
        }
      }
    

    You should use a stronger hash if you put thousands of arrays in the hash table. Check this post for an example.

提交回复
热议问题