Jon*_*eet 58
.NET中的数组不会覆盖Equals
或GetHashCode
,因此您将获得的值基本上基于引用相等(即默认实现Object
) - 对于值相等,您需要滚动自己的代码(或从第三个中找到一些派对).IEqualityComparer<byte[]>
如果您尝试将字节数组用作字典中的键等,则可能需要实现.
编辑:这是一个可重用的数组相等比较器,只要数组元素适当地处理相等,它应该没问题.请注意,在将数组用作字典中的键后,不得改变该数组,否则您将无法再次找到它 - 即使使用相同的引用也是如此.
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));
}
}
Run Code Online (Sandbox Code Playgroud)
简单的解决方案
public static int GetHashFromBytes(byte[] bytes)
{
return new BigInteger(bytes).GetHashCode();
}
Run Code Online (Sandbox Code Playgroud)
如果您使用 .NET 6 或至少 .NET Core 2.1,则可以使用System.HashCode结构编写更少的代码并获得更好的性能。
使用.NET 6 中提供的方法HashCode.AddBytes() :
public int GetHashCode(byte[] value)
{
var hash = new HashCode();
hash.AddBytes(value);
return hash.ToHashCode();
}
Run Code Online (Sandbox Code Playgroud)
使用.NET Core 2.1 中提供的方法HashCode.Add :
public int GetHashCode(byte[] value) =>
value.Aggregate(new HashCode(), (hash, i) => {
hash.Add(i);
return hash;
}).ToHashCode();
Run Code Online (Sandbox Code Playgroud)
请注意,在HashCode.AddBytes()的文档中它说:
此方法不保证添加字节范围的结果与单独添加相同字节的结果相匹配。
在这个Sharplab 演示中,它们只是输出相同的结果,但这可能因 .NET 版本或运行时环境而异。
归档时间: |
|
查看次数: |
22369 次 |
最近记录: |