重载运算符==后,如何比较两个变量是否指向同一个对象?
重载比较运算符,如何比较两个变量是否指向同一个对象(即不是值)
public static bool operator ==(Landscape a, Landscape b)
{
return a.Width == b.Width && a.Height == b.Height;
}
public static bool operator !=(Landscape a, Landscape b)
{
return !(a.Width == b.Width && a.Height == b.Height);
}
Overloading the comparison operator, how to compare if the two variables points to the same object(i.e. not value)
public static bool operator ==(Landscape a, Landscape b)
{
return a.Width == b.Width && a.Height == b.Height;
}
public static bool operator !=(Landscape a, Landscape b)
{
return !(a.Width == b.Width && a.Height == b.Height);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 Object.ReferenceEquals 静态方法。
当然,为了让 == 和 != 方法保留其全部功能,您还应该重写 Equals 和 GetHashCode,以便它们向调用者返回一组一致的响应。
Use the Object.ReferenceEquals static method.
Of course, in order for the == and != method to retain their full functionality, you should also be overriding Equals and GetHashCode so that they return a consistent set of responses to callers.
尝试
a.ReferenceEquals(b);
Try
a.ReferenceEquals(b);
检查两者是否指向同一个对象。 您应该使用 Object.ReferenceEquals 方法。 如果两者相同或均为 null,则返回 true。 否则会返回 false
To check whether both points to same object. You should use Object.ReferenceEquals method. It will return true if both are same or if both are null. Else it will return false
我知道这是一个老问题,但如果您要重载 == 或 Object.Equals 方法,您还应该重载反向运算符 !=。
在这种情况下,由于您要比较内部数字,因此应该重载其他比较运算符 <、>、<=、>=。
将来使用你的类的人,无论是第三方消费者,还是接管你代码的开发人员,可能会使用 CodeRush 或 Refactor 之类的东西,这会自动“翻转”逻辑(也称为反转条件)并然后将其展平,以摆脱 25 个嵌套 if 综合症。 如果他们的代码这样做了,并且您重载了 == 运算符而没有重载 != 运算符,则可能会改变代码的预期含义。
I know its an old question, but if you're going to overload the == or Object.Equals method, you should also overload the reverse operator !=.
And in this case, since you're comparing internal numbers, you should overload the other comparison operators <, >, <=, >=.
People who consume your class in the future, whether it be third-party consumers, or developers who take over your code, might use something like CodeRush or Refactor, that'll automatically "flip" the logic (also called reversing the conditional) and then flatten it, to break out of the 25 nested if's syndrome. If their code does that, and you've overloaded the == operator without overloading the != operator, it could change the intended meaning of your code.