我这样创建了一个字典:
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/