C# object comparison

空扰寡人 提交于 2019-12-02 03:20:36

问题


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.


回答1:


Overloading the == operator allows you to write x == y, which is much more natural than x.Equals(y), and will work even if x is null.




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/5212039/c-sharp-object-comparison

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!