为什么不Hashtable的回报如此"&的containsKey QUOT;类型为byte []在C#中的关键? [英] Why won't a Hashtable return true for "ContainsKey" for a key of type byte[] in C#?
本文介绍了为什么不Hashtable的回报如此"&的containsKey QUOT;类型为byte []在C#中的关键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑下面的代码:
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.
这篇关于为什么不Hashtable的回报如此"&的containsKey QUOT;类型为byte []在C#中的关键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文