为什么我的词典包含两个具有相同键的条目? [英] Why does my dictionary contain two entries with identical keys?
问题描述
我这样创建了字典:
Dictionary<byte[], MyClass> dic = new Dictionary<byte[], MyClass>();
假定密钥为20个字节的SHA1哈希.因此,在将两个条目添加到该字典中之后,我与调试器进行了检查,并且它们都具有相同的字节数组键.
the key is assumed to be a SHA1 hash of 20 bytes. So after having added two entries into that dictionary I checked with a debugger and both have the same byte array keys.
我以为字典不能做到这一点?
I thought dictionaries cannot do that?
PS:这是我添加它们的方式:
PS: Here's how I add them:
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);
推荐答案
字典不能(具有重复的键).
Dictionaries can't do that (have duplicate keys).
但是,您的词典没有具有重复的键,因为比较器将byte[]
视为引用,有效地使用了指针而不是数组的内容.
However, your dictionary doesn't have duplicate keys, because the comparator will treat byte[]
as a reference, effectively using the pointer rather than the content of the array.
如果要使用byte[]
作为键,可能最简单的解决方案是提供您自己的比较类,该类检查内容而不是参考值,例如:
If you want to use byte[]
as the key, probably the easiest solution is to provide your own comparison class which checks the content rather than the reference value, something like:
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());
这篇关于为什么我的词典包含两个具有相同键的条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!