You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为KeyedCollection<byte[],MyObject>设置默认自定义相等比较器防重复键

实现方案

你只需要在自定义Coll类的构造函数中,显式调用KeyedCollection基类的带相等比较器的构造重载,默认传入你编写的EquComparer即可,外部使用时不需要传任何参数,从根源上避免漏传比较器的问题。

修改后的代码如下:

public class Coll : KeyedCollection<byte[], MyObject>
{
    // 无参构造默认绑定自定义字节数组比较器
    public Coll() : base(new EquComparer())
    {
    }

    // 可选:如果需要自定义字典创建阈值的构造,同样默认绑定比较器
    public Coll(int dictionaryCreationThreshold) : base(new EquComparer(), dictionaryCreationThreshold)
    {
    }

    protected override byte[] GetKeyForItem(MyObject item) => item.Key;
}

额外优化建议

你当前的EquComparer的GetHashCode实现碰撞概率极高,内容顺序不同但字节和相同的数组会得到相同哈希值,会大幅降低集合的查找性能,建议替换为更可靠的哈希算法实现:

public class EquComparer : IEqualityComparer<byte[]>
{
    public bool Equals(byte[]? x, byte[]? y)
    {
        if (x is null && y is null) return true;
        if (x is null || y is null) return false;
        return x.SequenceEqual(y);
    }

    public int GetHashCode([DisallowNull] byte[] obj)
    {
        // FNV-1a哈希算法,适合处理字节序列,碰撞概率极低
        const int fnvPrime = 16777619;
        int hash = unchecked((int)2166136261);
        foreach (byte b in obj)
        {
            hash = (hash ^ b) * fnvPrime;
        }
        return hash;
    }
}

内容的提问来源于stack exchange,提问作者Eric Snyder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 02:54:04