byte 数组上的GetHashCode()

GetHashCode()byte[]数组上调用时计算什么? 具有相同内容的两个数据arrays不提供相同的散列。

像其他非原始的内置types一样,它只是返回任意的东西。 它绝对不会尝试散列数组的内容。 看到这个答案。

.NET中的数组不会覆盖EqualsGetHashCode ,所以您将得到的值基本上是基于引用相等(即Object的默认实现) – 为了实现值相等,您需要滚动自己的代码(或者find一些来自第三方)。 如果你想在字典中使用字节数组作为键,你可能需要实现IEqualityComparer<byte[]>

编辑:这是一个可重复使用的数组相等比较器应该是好的,只要数组元素处理相等适当。 请注意,在将字典作为字典中的键使用之后,您不得改变数组,否则即使使用相同的引用,也不能再次find它。

 using System; using System.Collections.Generic; public sealed class ArrayEqualityComparer<T> : IEqualityComparer<T[]> { // You could make this a per-instance field with a constructor parameter private static readonly EqualityComparer<T> elementComparer = EqualityComparer<T>.Default; public bool Equals(T[] first, T[] second) { if (first == second) { return true; } if (first == null || second == null) { return false; } if (first.Length != second.Length) { return false; } for (int i = 0; i < first.Length; i++) { if (!elementComparer.Equals(first[i], second[i])) { return false; } } return true; } public int GetHashCode(T[] array) { unchecked { if (array == null) { return 0; } int hash = 17; foreach (T element in array) { hash = hash * 31 + elementComparer.GetHashCode(element); } return hash; } } } class Test { static void Main() { byte[] x = { 1, 2, 3 }; byte[] y = { 1, 2, 3 }; byte[] z = { 4, 5, 6 }; var comparer = new ArrayEqualityComparer<byte>(); Console.WriteLine(comparer.GetHashCode(x)); Console.WriteLine(comparer.GetHashCode(y)); Console.WriteLine(comparer.GetHashCode(z)); Console.WriteLine(comparer.Equals(x, y)); Console.WriteLine(comparer.Equals(x, z)); } } 

byte[]objectinheritanceGetHashCode() ,它不覆盖它。 所以你得到的东西基本上是object的实现。

如果它不是相同的实例,它将返回不同的哈希值。 我猜这是基于内存地址,它以什么方式存储。