LLS*_*LLS 17 c# operator-overloading
当我尝试在C#中重载operator ==和!=并按推荐重写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;
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我想用的时候
if (temp == null)
Run Code Online (Sandbox Code Playgroud)
当temp真的为null时,会发生一些异常.并且我不能使用==来确定lhs是否为null,这将导致无限循环.
在这种情况下我该怎么办
我能想到的一种方法是给我们一些像Class.Equal(对象,对象)(如果它存在的话)在我做检查时绕过==.
解决问题的正常方法是什么?
谢谢.
Jak*_*sen 14
您可以在等于覆盖的顶部使用以下内容:
if (Object.ReferenceEquals(obj, null))
return false;
Run Code Online (Sandbox Code Playgroud)
您获得的异常可能是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);
}
Run Code Online (Sandbox Code Playgroud)
Lau*_*ble 12
您应该考虑在运算符重载中使用静态Equals方法(它将调用实例Equals方法):
public static bool operator ==(Complex lhs, Complex rhs)
{
return Equals(lhs, rhs);
}
public static bool operator !=(Complex lhs, Complex rhs)
{
return !Equals(lhs, rhs);
}
Run Code Online (Sandbox Code Playgroud)
注意:您也可以null使用Equals方法进行检查.
您还可以在MSDN上阅读Object.Equals主题,这是一个很好的样本来源.
| 归档时间: |
|
| 查看次数: |
3178 次 |
| 最近记录: |