当重写Equals()
法,MSDN recommends this:覆盖Equals():当调用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) {
//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
继承,然后如下相当于?注意电话:
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);
}
}
不,因为'!base.Equals(obj)'将返回true,导致Equals方法返回'false',如果它们不是完全相同的对象。如果他们是同一个对象,那么您的支票的其余部分将保证成功。它基本上会让你的重写无所事事。 – Rob
@Rob - 如果'!base.Equals(obj)'返回true,那么你*想*返回false。 –
'base.Equals(obj)'将检查当前对象和'obj'是否是*确切*相同的对象。也就是说,它们是指向内存中完全相同的对象的指针。如果它们是不同的对象,您的等于将立即返回false。如果它们*是*相同的对象,那么'GetType()== obj.GetType()'和'(x == px)&&(y == py)'都保证返回'true' – Rob