【发布时间】:2015-01-02 17:07:33
【问题描述】:
我有一个名为 Point 的类,它重载“==”和“!=”运算符来比较两个 Point 对象。如何将我的 Point 对象与“null”进行比较,这是一个问题,因为当我使用 null 调用 == 或 != 运算符时,在 Equals 方法中会出现问题。请打开一个控制台应用程序,看看我想说什么。我该如何解决它。
public class Point
{
public int X { get; set; }
public int Y { get; set; }
public static bool operator == (Point p1,Point p2)
{
return p1.Equals(p2);
}
public static bool operator != (Point p1, Point p2)
{
return !p1.Equals(p2);
}
public override bool Equals(object obj)
{
Point other = obj as Point;
//problem is here calling != operator and this operator calling this method again
if (other != null)
{
if (this.X == other.X && this.Y == other.Y)
{
return true;
}
return false;
}
else
{
throw new Exception("Parameter is not a point");
}
}
}
class Program
{
static void Main(string[] args)
{
Point p1 = new Point { X = 9, Y = 7 };
Point p2 = new Point { X = 5, Y = 1 };
p1.X = p2.X;
p1.Y = p2.Y;
bool b1=p1==p2;
Console.ReadKey();
}
}
【问题讨论】:
-
在运算符中检查
null,不要抛出。将值与 null 进行比较绝对不是例外情况。 -
您遇到什么错误?因为在我看来你的代码会导致无限循环?
-
感谢 Lasse V. Karlsen 解决了这个问题
-
请原谅这个无耻的插件,但由于这个问题太难了,我将只参考我的existing answer,它显示了在 .NET 中实现相等运算符的 One Right Way™,我将添加你也应该强烈考虑在你的课堂上实现
IEquatableinterface:这就是它的用途,人们粗鲁地忽略它。 :-( 哦,当覆盖Equals时,您必须也覆盖GetHashCode。否则会出现混乱。