我需要使用 byte[]
作为 Dictionary
中的键。由于 byte[]
不会覆盖默认的 GetHashCode
方法,因此包含相同数据的两个单独的 byte[]
对象将使用两个单独的槽在字典里。基本上我想要的是:
Dictionary<byte[], string> dict = new Dictionary<byte[], string>();
dict[new byte[] {1,2,3}] = "my string";
string str = dict[new byte[] {1,2,3}];
// I'd like str to be set to "my string" at this point
有没有简单的方法来做到这一点?我唯一能想到的是构建一个只包含 byte[]
的包装类,并根据 byte[] 的内容覆盖
,但这似乎很容易出错。GetHashCode
最佳答案
默认 byte[]
将通过引用进行比较,在这种情况下这不是您想要的。您需要做的是指定自定义 IEqualityComparer<byte[]>
并做你想要的比较。
例如
public class ByteArrayComparer : IEqualityComparer<byte[]> {
public bool Equals(byte[] left, byte[] right) {
if ( left == null || right == null ) {
return left == right;
}
return left.SequenceEqual(right);
}
public int GetHashCode(byte[] key) {
if (key == null)
throw new ArgumentNullException("key");
return key.Sum(b => b);
}
}
然后你可以做
var dict = new Dictionary<byte[], string>(new ByteArrayComparer());
2.0 的解决方案
public class ByteArrayComparer : IEqualityComparer<byte[]> {
public bool Equals(byte[] left, byte[] right) {
if ( left == null || right == null ) {
return left == right;
}
if ( left.Length != right.Length ) {
return false;
}
for ( int i= 0; i < left.Length; i++) {
if ( left[i] != right[i] ) {
return false;
}
}
return true;
}
public int GetHashCode(byte[] key) {
if (key == null)
throw new ArgumentNullException("key");
int sum = 0;
foreach ( byte cur in key ) {
sum += cur;
}
return sum;
}
}
关于c# - 使用 byte[] 作为字典中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1440392/