【发布时间】:2012-02-21 23:09:01
【问题描述】:
可能重复:
How do I check for nulls in an ‘==’ operator overload without infinite recursion?
我有一个看起来像这样的对象:
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;
}
}
这可以很好地用于比较实例,但我也希望能够处理如下表达式:
if(tags1 == null)
这样做会导致以下行出现异常:
return x.mask == y.mask;
因为y 是null。
我已尝试将此功能更改为:
public static bool operator ==(Tags x, Tags y)
{
if (x == null && y == null) return true;
if (x == null || y == null) return false;
return x.mask == y.mask;
}
但是,这会导致堆栈溢出,因为实现使用自己的覆盖比较运算符。
让== 运算符处理与null 的比较的诀窍是什么?谢谢!
【问题讨论】:
-
看到这个[问题][1]。 [1]:stackoverflow.com/questions/73713/…
-
@MichaelLiu:你认为究竟是什么错误?
-
唉,我误读了答案。没有错误。我会删除我的评论。
-
@KonradRudolph 它更像是 Rohan West 的链接的副本..
-
@nawfal 我不同意。 narrow 问题在 Rohan 的链接中得到了回答,但更广泛的问题——如何在语义上正确地实现相等检查——在另一个问题中得到了广泛的回答。
标签: c# .net operator-overloading