Possible Duplicate:
How do I check for nulls in an '==' operator overload without infinite recursion?
当我为对象重载 == 运算符时,我通常会这样写:
public static bool operator ==(MyObject uq1, MyObject uq2) {
if (((object)uq1 == null) || ((object)uq2 == null)) return false;
return uq1.Field1 == uq2.Field1 && uq1.Field2 == uq2.Field2;
}
如果您不向下转换为 object 函数会递归到自身,但我想知道是否有更好的方法?
正如微软所说,
A common error in overloads of
operator == is to use (a == b), (a ==
null), or (b == null) to check for
reference equality. This instead
results in a call to the overloaded
operator ==, causing an infinite loop.
Use ReferenceEquals or cast the type
to Object, to avoid the loop.
所以使用 ReferenceEquals(a, null) || ReferenceEquals(b, null) 是一种可能性,但转换为 object 也同样好(我相信实际上是等价的)。
所以是的,似乎应该有更好的方法,但您使用的方法是推荐的方法。
但是,正如已经指出的那样,在覆盖 == 时,您确实也应该覆盖 Equals。由于 LINQ 提供程序是用不同的语言编写的,并在运行时进行表达式解析,即使您自己拥有所有代码,谁知道什么时候您会因不这样做而受到伤害。