c# - 使用 byte[] 作为字典中的键

标签 c#

我需要使用 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/

相关文章:

c# - 使用 EDSDK 2.9 从佳能相机中检索图片

c# - Json.NET 中的 JConstructor 和 JRaw

c# - HttpContext.Current.GetOwinContext().Authentication.Challenge() 不打开 adfs 页面

c# - 并发字典 : How do I add if value does not exist or condition fails?

c# - aspnet vNext ActionFilter 和 TempData

c# - VSTO Add-In 是否支持 Mac(iOS) 操作系统?

c# - Thread.Sleep(timeout) 和 ManualResetEvent.Wait(timeout) 有什么区别?

c# - 了解一次性元素

c# - 列出 Azure 表值

c# - 美化从 C# 代码块中剥离泛型