无法调试GetHashCode方法

时间:2017-08-17 09:29:03

标签: c# data-structures iequalitycomparer

我已经以下面的方式实现了相等比较器。

class BoxEqualityComparer : IEqualityComparer<Box>
{
    public bool Equals(Box b1, Box b2)
    {
        if (b2 == null && b1 == null)
           return true;
        else if (b1 == null | b2 == null)
           return false;
        else if(b1.Height == b2.Height && b1.Length == b2.Length
                            && b1.Width == b2.Width)
            return true;
        else
            return false;
    }

    public int GetHashCode(Box bx)
    {
        int hCode = bx.Height ^ bx.Length ^ bx.Width;
        return hCode.GetHashCode();
    }
}

然后我创建了一个Dictionary,我将添加一些值。所以这里它将基于它的属性(高度,宽度,长度)来比较对象。我得到了预期的输出。但我想知道GetHashCode方法的执行情况。 我在那里放了一个断点,但是我无法调试它。我的问题是GeHashCode方法何时执行以及执行了多少次?

class Example
{
   static void Main()
   {
      BoxEqualityComparer boxEqC = new BoxEqualityComparer();

      var boxes = new Dictionary<Box, string>(boxEqC);

      var redBox = new Box(4, 3, 4);
      AddBox(boxes, redBox, "red");

      var blueBox = new Box(4, 3, 4);
      AddBox(boxes, blueBox, "blue");

      var greenBox = new Box(3, 4, 3);
      AddBox(boxes, greenBox, "green");
      Console.WriteLine();

      Console.WriteLine("The dictionary contains {0} Box objects.",
                        boxes.Count);
   }

   private static void AddBox(Dictionary<Box, String> dict, Box box, String name)
   {
      try {
         dict.Add(box, name);
      }
      catch (ArgumentException e) {
         Console.WriteLine("Unable to add {0}: {1}", box, e.Message);
      }
   }
}

public class Box
{
    public Box(int h,  int l, int w)
    {
        this.Height = h;
        this.Length = l;
        this.Width = w;
    }

    public int Height { get; set; }
    public int Length { get; set; }
    public int Width { get; set; }

    public override String ToString()
    {
       return String.Format("({0}, {1}, {2})", Height, Length, Width);
    }
}

1 个答案:

答案 0 :(得分:0)

请参阅https://referencesource.microsoft.com/#mscorlib/system/collections/generic/dictionary.cs,fd1acf96113fbda9

Add(key,value)调用insert方法,而insert方法总是通过

计算哈希码
try{
       JSONObject jsonObject = new JSONObject(response);
        String token = jsonObject.getJSONObject("data").getString("token");
}
catch(JSONException e){
e.printstacktrace();
}

换句话说,每次调用Dictionary.Add都应该总是通过你提供的IEqualityComparer触发键的哈希计算。

至于你的示例代码,这对我来说很好,VS 2015确实在我的BoxEqualityComparer.GetHashCode()中打破了。