Operator overloading and different types

前端 未结 5 1539
轮回少年
轮回少年 2021-01-04 09:33

I have a class Score which is going to be heavily used in comparisons against integers. I was planning on overloading the == operator to enable these comparisons as per th

5条回答
  •  太阳男子
    2021-01-04 10:02

    I do think this is a strange situation to use an operator overload, but it is your call.

    However, my main point is that if you overload == you will also be required to overload !=

    If you then overload !=, the part where you compare x to check that it is not null using x != null will cause, the == operator to call the != operator. This isn't a problem in itself, as long as this doesn't then use a == comparison, as you will have a recursive set of calls, leading to a stack-overflow.

    However since a lot of people when overloading != implement it as 'not ==' - in your case this will cause a stack overflow.

    Solution: particularly in overloading ==, != and Equals(), its best to use use Object.ReferenceEquals(x, null); when comparing to null.

提交回复
热议问题