开发者

Overloading +=, +, ==, and != operators [duplicate]

开发者 https://www.devze.com 2023-03-28 17:43 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Why must we define both == and != in C#?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Why must we define both == and != in C#?

Why is overloading of += possible only by overloading of +, but == and != are separately overloaded?

It seems it should be inverted.

+= overloading is nearly always possible to write more effective because it's unnecessary to allocate memory for new object. But I c开发者_如何学Goan't invent an example in which operators == and != should be different in something except inverting the result Equals().


A similar question has been asked before.

The biggest reason is that when you overload the == and != operators, you don't have to return a boolean. If you're not returning a boolean, you can't just invert the complimentary operator. There are other possible reasons they are separately overloaded, you can view the answers to that question for those other reasons.

There is a valid reason you can't overload += and therefore it is done implicitly via the + operator. I has to do with the fact that you can't override the assignment operator in C#, it's part of the language standard. The += is increment and assign, the latter of which you can't overload in C#.

0

精彩评论

暂无评论...
验证码 换一张
取 消