重写Equals():调用base.Equals()时是否为空冗余比较?

时间:2015-07-20 23:51:40

标签: c# inheritance equality

覆盖Equals()方法时,MSDN recommends this

class Point: Object {
   protected int x, y;

   public Point(int X, int Y) {
      this.x = X;
      this.y = Y;
   }

   public override bool Equals(Object obj) {

      //Check for null and compare run-time types.
      if (obj == null || GetType() != obj.GetType()) return false;

      Point p = (Point)obj;

      return (x == p.x) && (y == p.y);
   }
}

但是如果我们知道子类直接继承自Object,那么是以下等价的?请注意!base.Equals()来电:

class Point: Object {
   protected int x, y;

   public Point(int X, int Y) {
      this.x = X;
      this.y = Y;
   }

   public override bool Equals(Object obj) {

      if (!base.Equals(obj) || GetType() != obj.GetType()) return false;

      Point p = (Point)obj;

      return (x == p.x) && (y == p.y);
   }
}

1 个答案:

答案 0 :(得分:5)

如果this引用null你是对的,那么支票可以(但似乎不能保证)是多余的,如RuntimeHelpers.Equals所述的!base.Equals(obj)实施中所示。 this answer

但是,Equals检查会破坏您的null。当引用不是!base.Equals - true时,对于任何不同的引用,不仅会为null值生成Point x = new Point(1,2); Point y = new Point(1,2); Console.WriteLine(x.Equals(y)); // will print 'False'

出现问题的情况是:

x

即使ybase.Equal在业务逻辑方面相同,但它们是不同的对象,因此false会返回Book::storeBook(...)