Is it necessary to override == and != operators wh

2019-02-16 14:43发布

Or it's advisable to do that? Why?

9条回答
Deceive 欺骗
2楼-- · 2019-02-16 15:00

It would be advisable, as it would be unexpected if:

if (foo == bar)

...behaved differently to:

if (foo.Equals(bar))
查看更多
三岁会撩人
3楼-- · 2019-02-16 15:00

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

查看更多
We Are One
4楼-- · 2019-02-16 15:08

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

查看更多
Explosion°爆炸
5楼-- · 2019-02-16 15:10

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.

查看更多
该账号已被封号
6楼-- · 2019-02-16 15:12

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.

查看更多
我想做一个坏孩纸
7楼-- · 2019-02-16 15:15

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.

查看更多
登录 后发表回答