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

前端 未结 4 1420
一个人的身影
一个人的身影 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:53

    By default reference types are compared by their references, unless the Equals method for that type has been overidden.

    Because you want to use the reference type as a key in a has table you should also override the GetHashCode method, so that objects that are 'equal' produce the same hash code.

    A hash table stores objects by computing the hash using the GetHashCode method, and any later 'hits' are calculated using this. You can do this by basing the value returned by GetHasshCode on each of the properties of the object, in your case each of the bytes in the array. This is an example of where I used it you can also do this in an IEqualityComparer which you could use in your hashtable:

     public override int GetHashCode() {
            int hash = 17;
      hash = hash * 23 + DrillDownLevel.GetHashCode();
      hash = hash * 23 + Year.GetHashCode();
    
      if (Month.HasValue) {
        hash = hash * 23 + Month.Value.GetHashCode();
      }
    
      if (Week.HasValue) {
        hash = hash * 23 + .Week.Value.GetHashCode();
      }
    
      if (Day.HasValue) {
        hash = hash * 23 + obj.Day.Value.GetHashCode();
      }
    
      return hash;
    }
    

提交回复
热议问题