byte[] 数组上的 GetHashCode()

2023-12-23

什么是GetHashCode()调用时计算byte[]大批? 具有相同内容的 2 个数据数组不提供相同的哈希值。


.NET 中的数组不会覆盖Equals or GetHashCode,因此您将获得的值基本上基于引用相等性(即默认实现Object) - 为了价值平等,您需要滚动自己的代码(或从第三方找到一些代码)。您可能想要实施IEqualityComparer<byte[]>如果您尝试使用字节数组作为字典等中的键。

编辑:这是一个可重用的数组相等比较器,只要数组元素正确处理相等就应该没问题。请注意,您mustn't在将数组用作字典中的键后对其进行变异,否则即使使用相同的引用,您也将无法再次找到它。

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));
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

byte[] 数组上的 GetHashCode() 的相关文章

随机推荐