为什么哈希表不会为“ContainsKey"返回 true?对于 C# 中 byte[] 类型的键? [英] Why won't a Hashtable return true for "ContainsKey" for a key of type byte[] in C#?

查看:30
本文介绍了为什么哈希表不会为“ContainsKey"返回 true?对于 C# 中 byte[] 类型的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

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

Hashtable ht = new Hashtable();
ht.Add(bytes, "hi");
Assert.IsTrue(ht.ContainsKey(another));

为什么这个断言会失败?作为原始类型的数组不应该使用对象引用,对吗?那么为什么它会返回false呢?我可以做些什么来使这个哈希表正常工作?

Why does this assertion fail? Being an array of a primitive type shouldn't use using the object reference, should it? So why would it return false? Is there anything I can do to make this hashtable work?

推荐答案

这是一个示例实现:

  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.

这篇关于为什么哈希表不会为“ContainsKey"返回 true?对于 C# 中 byte[] 类型的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆