温馨提示×

C# byte数组能作为哈希键吗

c#
小樊
85
2024-07-13 12:38:28
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C#中,byte数组可以作为哈希键,只要符合哈希键的要求。哈希键必须是不可变的,并且需要实现GetHashCode()和Equals()方法。在使用byte数组作为哈希键时,可以自定义一个类来包装byte数组,并实现这些方法。例如:

public class ByteArrayKey
{
    private byte[] key;

    public ByteArrayKey(byte[] key)
    {
        this.key = key;
    }

    public override int GetHashCode()
    {
        unchecked
        {
            int hash = 17;
            foreach (byte b in key)
            {
                hash = hash * 31 + b.GetHashCode();
            }
            return hash;
        }
    }

    public override bool Equals(object obj)
    {
        if (obj is ByteArrayKey other)
        {
            return key.SequenceEqual(other.key);
        }
        return false;
    }
}

然后可以使用这个ByteArrayKey类作为哈希键,例如:

var dictionary = new Dictionary<ByteArrayKey, string>();

byte[] key1 = new byte[] { 0x01, 0x02, 0x03 };
byte[] key2 = new byte[] { 0x04, 0x05, 0x06 };

dictionary[new ByteArrayKey(key1)] = "Value1";
dictionary[new ByteArrayKey(key2)] = "Value2";

Console.WriteLine(dictionary[new ByteArrayKey(key1)]); // Output: Value1
Console.WriteLine(dictionary[new ByteArrayKey(key2)]); // Output: Value2

这样就可以使用byte数组作为哈希键了。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:如何用C#进行哈希加密

0