Or it's advisable to do that? Why?
相关问题
- Generic Generics in Managed C++
- How to Debug/Register a Permanent WMI Event Which
- 'System.Threading.ThreadAbortException' in
- Bulk update SQL Server C#
- Should I use static function in c# where many call
It would be advisable, as it would be unexpected if:
...behaved differently to:
in A.Equals(B) A cannot be null in A == B either can be null
In addition to all the answers already here, don't forget to ensure
GetHashCode()
is consistent as well.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.
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.
See the guidelines for overriding Equals() and operator==.
Quote:
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.