Is it necessary to override == and != operators when overriding the Equals method? (.NET)

后端 未结 9 1186
一向
一向 2021-01-11 19:06

Or it\'s advisable to do that? Why?

相关标签:
9条回答
  • 2021-01-11 19:11

    in A.Equals(B) A cannot be null in A == B either can be null

    0 讨论(0)
  • 2021-01-11 19:13

    Overriding == to make it call Equals strikes me as a generally bad idea for reference types. If you override == to make it call Equals, then I don't think there's a way for a user of your code to test whether two object references refer to the exact same object (versus an object with equal properties).

    If people want to test instances of your classes for value equality then surely they should just call Equals, saving == for testing reference equality specifically.

    0 讨论(0)
  • It would be advisable, as it would be unexpected if:

    if (foo == bar)
    

    ...behaved differently to:

    if (foo.Equals(bar))
    
    0 讨论(0)
  • 2021-01-11 19:20

    It is not necessary, nobody will kill you if you do not do that.

    However, do notice that it is often more natural to write (A == B) than A.Equals(B). If you provide both methods, it will be easier for consumers of your code.

    0 讨论(0)
  • 2021-01-11 19:23

    If you are overriding the equals method and still want to be able to check for equality (or inequality) then you should probably override the == and != methods as well.

    0 讨论(0)
  • 2021-01-11 19:27

    See the guidelines for overriding Equals() and operator==.

    Quote:

    By default, the operator == tests for reference equality by determining whether two references indicate the same object. Therefore, reference types do not have to implement operator == in order to gain this functionality. When a type is immutable, that is, the data that is contained in the instance cannot be changed, overloading operator == to compare value equality instead of reference equality can be useful because, as immutable objects, they can be considered the same as long as they have the same value. It is not a good idea to override operator == in non-immutable types.

    Basically:

    If you want == and != to behave like Equals(..) and !Equals(..) you need to implement the operators. You typically do this only with immutable types.

    0 讨论(0)
提交回复
热议问题