c# - 为什么我的字典包含两个键相同的条目?

标签 c# .net dictionary

我这样创建了一个字典:

Dictionary<byte[], MyClass> dic = new Dictionary<byte[], MyClass>();

key 被假定为 20 字节的 SHA1 散列。因此,在向该字典中添加两个条目后,我使用调试器进行了检查,发现它们都具有相同的字节数组键。

我以为字典不能那样做?

PS:这是我添加它们的方式:

string strText1 = "text";

SHA1 sha1_1 = new SHA1CryptoServiceProvider();
byte[] bytesHash1 = sha1_1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strText1));

string strText2 = "text";

SHA1 sha1_2 = new SHA1CryptoServiceProvider();
byte[] bytesHash2 = sha1_2.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strText2));

dic.Add(bytesHash1, 1);
dic.Add(bytesHash2, 2);

最佳答案

字典不能这样做(有重复键)。

但是,您的字典没有有重复键,因为比较器会将 byte[] 视为引用,有效地使用指针而不是内容数组。

如果您想使用 byte[] 作为键,最简单的解决方案可能是提供您自己的比较类来检查内容而不是引用值,例如:

public class BaComp: IEqualityComparer<byte[]> {
    public bool Equals (byte[] left, byte[] right) {
        // Handle case where one or both is null (equal only if both are null).

        if ((left == null) || (right == null))
            return (left == right);

        // Otherwise compare array sequences of two non-null array refs.

        return left.SequenceEqual (right);
    }

    public int GetHashCode (byte[] key) {
        // Complain bitterly if null reference.

        if (key == null)
            throw new ArgumentNullException ();

        // Otherwise just sum bytes in array (one option, there are others).

        int rc = 0;
        foreach (byte b in key)
            rc += b;
        return rc;
    }
}

然后像这样使用它:

Dictionary<byte[], MyClass> dic = new Dictionary<byte[], MyClass> (new BaComp());

关于c# - 为什么我的字典包含两个键相同的条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15941389/

相关文章:

c# - 从 Windows 上的 C# 迁移到 Mac 上的 Objective-C

c# - C# 中 assoc-diff 的名称

c# - DateTime.ParseExact 根本不起作用,为什么?

c# - 如何在特定位置覆盖 WPF 控件

c# - 对象引用 = 字符串引用;换一个不影响另一个?

c# - 如何在 Azure 函数中使用带有主题/订阅的服务总线触发器

c# - 如何通过 C# 在 SharePoint 2007 列表中获取仅包含用户创建字段的列表?

c++ - 我在哪种情况下 std::map<A,B> 比排序的 std::vector<std::pair<A,B>> 更快?

Javascript 或 jQuery png 播放器

c# - C# 中的字典枚举