gpt4 book ai didi

c# - byte[] 数组上的 GetHashCode()

转载 作者:IT王子 更新时间:2023-10-29 03:48:57 26 4
gpt4 key购买 nike

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

最佳答案

.NET 中的数组不会覆盖 EqualsGetHashCode ,因此您将获得的值基本上基于引用相等性(即 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));
}
}

关于c# - byte[] 数组上的 GetHashCode(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7244699/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com