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

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

image

经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 可能会有问题,先放这里,随后再看。

posted @ 2011-12-01 16:36  张保维  阅读(439)  评论(1编辑  收藏  举报