重载运算符 == 检查两个对象的相等性
昨天我询问有关使用重载运算符的问题,但没有人提到它很常见,并且经常用于检查两个对象(如字符串、颜色)的相等性。
此外,在这种情况下,如果我的类型表示一些可以检查的对象,则重载 == 是正确的确保其字段的公平性等。当然,我的意思并不是检查变量是否指向同一个对象。
Yesterday I asked about using overloading operators and nobody mentioned that its quite common and often used to check equity of two objects like strings, colors..
Also in this case it is correct to overload == if my types represent some objects that could be checked for equity of their fields etc. Sure I do not mean checking whether the variables point to the same object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,重载
==
运算符(当然,同时重载!=
)是合理的。您需要意识到它是重载而不是覆盖,因此如果您曾经有过:
无论您做了什么,都会检查引用是否相等。
Yes, it's reasonable to overload the
==
operator (and!=
at the same time, of course).You need to be aware that it is overloading rather than overriding, so if you ever have:
that will check for reference equality regardless of what you've done.
您基本上可以自己决定公平的含义。如果您认为某些字段相同,那么请检查一下。
You can basically decide yourself what equity means. If it's to you that some fields are the same, then sure, check for that.
在我看来,最好使用 == 检查引用相等性,并使用 .Equals(Object obj) 自定义相等性。
这样您将有两种比较方法,而不是一种。
无论如何,请记住,如果您重新定义 Equality,您也应该重新定义 GetHashCode(),以便两个相等的对象返回相同的哈希码。
In my opinion is better to use == to check for reference equality and use .Equals(Object obj) for custom equality.
That way you will have two ways of comparing instead of one.
Anyway take in mind that if you redefine Equality you should redefine the GetHashCode() too so two objects that are equal return the same hash code.
不太确定你的问题是什么,因为你似乎已经自己回答了。
您可以重载运算符==等来检查两个对象是否相同,因此在字符串或颜色的示例中,两个字符串具有相同的实际内容,或者两种颜色具有相同的RGB值。正如您所说,这与指向同一对象的两个变量不同。
您可能需要查看 MSDN 部分
运算符重载 参阅教程
有关重载的更多信息,请
。类似的问题提供更多信息,包括可以重载的运算符列表:
为什么 C# 不允许运算符重载?
Not quite sure what your question is, in that you seem to have answered it yourself.
You can overload operator== etc to check that two objects are the same, so in your examples of strings or colours, that two strings have the same actual contents, or that two colours have the same RGB values. As you say, this is distinct from two variables pointing at the same object.
You might want to check out the MSDN section
Operator Overloading Tutorial
for more information on overloading.
Similar question with more information, including a list of the operators that you can overload:
why C# not allow operator overloading?