简体   繁体   中英

C# object comparison

Could someone point out the idea of overloading operator== to perform deep object comparison (instead of reference comparison).

From MSDN:

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.

When would it actually benefit?

And, like, if every object has method Equals , which makes value comparison possible, why would someone ever perform value (not reference) comparison using x == y statement?

I guess I don't understand something, because this looks very weird to me.

重载==运算符使您可以编写x == y ,它比x.Equals(y)自然得多,即使x为null也会起作用。

overloading operator == only improves the readability of your code. Always use .Equals() for the types you define, especially for deep object comparison.

System.String is the classic example of a reference type that benefits from a deep value equality comparison instead of a reference comparison.

In general, there are some circumstances where it makes code easier to write and the meaning of the equality is better expressed by a value comparison than by a reference comparison.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM