C#对象比较 [英] C# object comparison
问题描述
有人会指出重载运算符==
以执行深对象比较(而不是引用比较)的想法。
从MSDN:
通过确定两个引用是否指示相同的对象来测试引用相等性。因此,引用类型不必实现operator ==以获得此功能。当一个类型是不可变的,也就是说,包含在实例中的数据不能被改变,重载operator ==来比较值相等而不是引用相等是有用的,因为作为不可变的对象,它们可以被认为是long因为它们具有相同的值。
实际上什么时候会受益?
而且,如果每个对象都有方法 Equals
,这使得值比较成为可能,为什么有人会执行 value使用 x == y
语句进行比较?
重载 ==
运算符允许您写 x == y
,这比 x.Equals )
,即使 x
为空也会工作。
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.
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.
这篇关于C#对象比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!