gpt4 book ai didi

c# - 运算符重载报错

转载 作者:行者123 更新时间:2023-11-30 20:24:26 25 4
gpt4 key购买 nike

我有一个名为 Point 的类,它重载“==”和“!=”运算符来比较两个 Point 对象。我怎样才能将我的 Point 对象与“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();
}
}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com