当我尝试在 C# 中重载运算符 == 和 !=,并按照建议覆盖 Equal 时,我发现我无法区分普通对象和 null。例如,我定义了一个 Complex 类。
public static bool operator ==(Complex lhs, Complex rhs)
{
return lhs.Equals(rhs);
}
public static bool operator !=(Complex lhs, Complex rhs)
{
return !lhs.Equals(rhs);
}
public override bool Equals(object obj)
{
if (obj is Complex)
{
return (((Complex)obj).Real == this.Real &&
((Complex)obj).Imaginary == this.Imaginary);
}
else
{
return false;
}
}
但是当我想用
if (temp == null)
当 temp 真的为 null 时,会发生一些异常。而且不能用==判断lhs是否为null,会死循环。
遇到这种情况我该怎么办。
我能想到的一种方法是让我们在进行检查时绕过 ==,比如 Class.Equal(object, object)(如果存在)。
解决问题的正常方法是什么?
谢谢。
最佳答案
您可以在 Equals 覆盖的顶部使用以下内容:
if (Object.ReferenceEquals(obj, null))
return false;
您遇到的异常可能是 StackOverflowException,因为您的 == 运算符会导致无限递归。
编辑:
如果 Complex 是一个结构体,那么 NullReferenceExceptions 就不会有任何问题。如果 Complex 是一个类,您可以更改 == 和 != 运算符重载的实现以避免异常(Laurent Etiemble 已经在他的回答中指出了这一点):
public static bool operator ==(Complex lhs, Complex rhs)
{
return Equals(lhs, rhs);
}
public static bool operator !=(Complex lhs, Complex rhs)
{
return !Equals(lhs, rhs);
}
关于c# - 重载 == (当然还有 != )运算符,我可以绕过 == 来判断对象是否为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3005794/