我有一个看起来像这样的对象:
public class Tags
{
int mask;
public static bool operator !=(Tags x, Tags y)
{
return !(x == y);
}
public static bool operator ==(Tags x, Tags y)
{
return x.mask == y.mask;
}
}
Run Code Online (Sandbox Code Playgroud)
这适用于将实例相互比较,但我也希望能够处理如下表达式:
if(tags1 == null)
Run Code Online (Sandbox Code Playgroud)
这样做会导致以下行出现异常:
return x.mask == y.mask;
Run Code Online (Sandbox Code Playgroud)
既然y是null.
我已经尝试将此功能更改为:
public static bool operator ==(Tags x, Tags y)
{
if (x == null && y == null) return true;
if (x == null || y == null) …Run Code Online (Sandbox Code Playgroud) 我在我的类上重载了==运算符,如下所示:
public static bool operator ==(Table pt1, Table pt2) {
return Compare(pt1, pt2) == 0 && pt1.TableName == pt2.TableName;
}
Run Code Online (Sandbox Code Playgroud)
比较将像strcmp在c ++中一样工作,返回一个整数.问题是,如果我执行if(MY_CLASS == null),它将调用我的==运算符,从而调用我的Compare函数.什么是alternatiev?检查pt1和pt2以查看它们是否为空?或者只是在pt2?
我有一个类,我想在c#中重载==运算符.我已经有一个正常的.Equals覆盖.当我尝试使用我的==运算符时,它在我的对象(Person)上给了我一个空引用异常.如果我尝试检查它是否为null,它将依次调用相同的运算符来检查它是否为null并创建一个无限循环.这似乎是一个巨大的缺陷,我无法找到正确的方法来做到这一点.
public static bool operator ==(Person person, object obj)
{
return person == null ? person.Equals(obj) : false;
}
public static bool operator !=(Person person, object obj)
{
return !(person == obj);
}
Run Code Online (Sandbox Code Playgroud) 我有一个名为 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 …Run Code Online (Sandbox Code Playgroud) 我有一个名为"Criterion"的类,我想实现==运算符,但我正在努力解决以下问题:
当我实现==运算符时,我正在检查我的一个或两个实例是否为空,但是当我这样做时,它会导致递归调用==然后我得到"StackOverflow"(他)异常.
从技术上讲,我可以实现Equals运算符而不是覆盖==,但如果我实现了==运算符,代码将更具可读性.
这是我的代码:
public static bool operator == (Criterion c1, Criterion c2)
{
if (null == c1)
{
if (null == c2)
return true;
return false;
}
if (null == c2)
return false;
if ((c1.mId == c2.mId) && (c1.mName == c2.mName))
return true;
return false;
}
Run Code Online (Sandbox Code Playgroud)