kdb*_*man 6 c# inheritance equality
覆盖该Equals()方法时,MSDN建议:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
但是如果我们知道子类直接继承自的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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果this引用是null对的,那么检查可以(但似乎不能保证)是多余的,如本答案中RuntimeHelpers.Equals引用的实现中所示.
但是,!base.Equals(obj)支票会打破你的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'
Run Code Online (Sandbox Code Playgroud)
尽管x并且y在业务逻辑方面是相同的,但它们是不同的对象,因此base.Equal返回false.