有人可以指出重载 operator==
来执行深度对象比较的想法吗(而不是引用比较)。
来自 MSDN:
默认情况下,运算符 == 通过确定两个引用是否指示同一对象来测试引用相等性。因此,引用类型不必实现运算符 == 即可获得此功能。当类型不可变时,即实例中包含的数据无法更改时,重载运算符 == 来比较值相等而不是引用相等可能很有用,因为作为不可变对象,它们可以被视为与 long 相同因为它们具有相同的值。在非不可变类型中重写运算符 == 不是一个好主意。
什么时候才能真正受益呢?
而且,如果每个对象都有方法 Equals
,这使得值比较成为可能,为什么有人会使用以下方法执行值(不是引用)比较x == y
语句?
我想我不明白一些事情,因为这对我来说看起来很奇怪。
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.
发布评论
评论(3)
重载
==
运算符允许您编写x == y
,这比x.Equals(y)
更自然,并且将即使x
为 null 也能工作。Overloading the
==
operator allows you to writex == y
, which is much more natural thanx.Equals(y)
, and will work even ifx
is null.重载运算符
==
只会提高代码的可读性。始终对您定义的类型使用 .Equals(),特别是对于深度对象比较。overloading operator
==
only improves the readability of your code. Always use .Equals() for the types you define, especially for deep object comparison.System.String
是引用类型的经典示例,它受益于深度值相等比较而不是引用比较。一般来说,在某些情况下,它使代码更容易编写,并且通过值比较比通过引用比较更好地表达相等的含义。
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.