简体   繁体   English

C#对象比较

[英]C# object comparison

Could someone point out the idea of overloading operator== to perform deep object comparison (instead of reference comparison). 有人可以指出重载operator==来执行深度对象比较(而不是引用比较)的想法

From MSDN: 来自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? 而且,例如,如果每个对象都有方法Equals ,这使值比较成为可能,那么为什么有人会使用x == y语句执行 (而不是引用)比较?

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. 始终对定义的类型使用.Equals(),尤其是对于深层对象比较。

System.String is the classic example of a reference type that benefits from a deep value equality comparison instead of a reference comparison. System.String是引用类型的经典示例,它受益于深度值相等比较而不是引用比较。

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. 通常,在某些情况下,它使代码更易于编写,并且通过值比较比通过引用比较更好地表示相等性的含义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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