今天在使用 Hbase 的Thrift接口的时候, C# 生成的代码出现错误为, “给定的关键字不在字典中”

Dictionary<byte[],string> 出现错误的解决方案

经google 后找到答案, 原地址为: http://stackoverflow.com/questions/1440392/use-byte-as-key-in-dictionary

 

下面是我的测试代码,原代码中 有一个错误  “ <> “ 要改为“!=” 就好了。

 

 

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;
      }
  }
   

  //public class ByteArrayComparer : IEqualityComparer<byte[]>
  //{
  //    public bool Equals(byte[] left, byte[] right)
  //    {
  //        if (left == null || right == null)
  //        {
  //            return left == right;
  //        }
  //        return left.Equals(right);
  //        //return left.SequenceEquals(right);
  //    }
  //    public int GetHashCode(byte[] key)
  //    {
  //        if (key == null)
  //            throw new ArgumentNullException("key");

  //      return  key.GetHashCode();
  //        //return key.Sum();
  //    }
  //}

 

  class Program
  {

      static void Main(string[] args)
      {

          Dictionary<byte[], string> dic = new Dictionary<byte[], string>(new ByteArrayComparer());
          dic.Add("key".ToBytes(), "zbbb");
          Console.WriteLine(dic["key".ToBytes()]);
}

}

 

注意 gethashcode 可能会有问题,先放这里,随后再看。

相关文章:

  • 2022-12-23
  • 2021-05-19
  • 2021-11-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-25
  • 2022-12-23
猜你喜欢
  • 2021-06-25
  • 2018-03-12
  • 2021-06-20
  • 2021-09-11
  • 2021-12-06
  • 2022-12-23
相关资源
相似解决方案