这是一个示例实现:
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;
}
}
}
如果将数千个数组放入哈希表中,则应使用更强的哈希。查看此帖子以获取示例。