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

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

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

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

    It is not necessary, but a smart thing to do.

    If you are creating a framework and another developer other than you are going to use the object you should override the == and !=. That way when a developer may use it they at least have the right logic to compare the 2 objects rather than just are the same in memory.

    I would ensure that your == & != do call your equals method.

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

    See Guidelines for Implementing Equals and the Equality Operator (==)

    For Value Types (structs) "Implement == any time you override the Equals method"

    For Reference Types (classes), "Most reference types, even those that implement the Equals method, should not override ==." The exception is for immutable classes and those with value-like semantics.

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

    In addition to all the answers already here, don't forget to ensure GetHashCode() is consistent as well.

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