运算符重载给出错误

erh*_*run 3 .net c#

我有一个名为 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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

ang*_*son 5

使用ReferenceEquals检查null

if (ReferenceEquals(other, null))
Run Code Online (Sandbox Code Playgroud)

话虽如此,Equals如果遇到未知的对象类型,通常不应该抛出异常,它应该只返回false,因此这是我要编写的方法:

public override bool Equals(object obj)
{
    Point other = obj as Point;

    if (ReferenceEquals(other, null))
        return false;

    return (this.X == other.X && this.Y == other.Y);
}
Run Code Online (Sandbox Code Playgroud)

另一个问题是,如果您null与某些内容进行比较,您的运算符将引发异常,因为您无法在null引用上调用实例方法。

因此,这是我会写的完整课程:

public class Point
{
    public int X { get; set; }
    public int Y { get; set; }


    public static bool operator == (Point p1,Point p2)
    {
        if (ReferenceEquals(p1, p2)) return true;
        if (ReferenceEquals(p1, null)) return false;
        return p1.Equals(p2);
    }

    public static bool operator != (Point p1, Point p2)
    {
        return !(p1 == p2);
    }

    public bool Equals(Point other)
    {
        if (ReferenceEquals(other, null))
            return false;

        return (this.X == other.X && this.Y == other.Y);
    }

    public override bool Equals(object obj)
    {
        Point other = obj as Point;
        if (ReferenceEquals(other, null))
            return false;
        return Equals(other);
    }
}
Run Code Online (Sandbox Code Playgroud)