C# 对象比较

发布于 2024-10-20 16:51:22 字数 494 浏览 3 评论 0 原文

有人可以指出重载 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

绮烟 2024-10-27 16:51:22

重载 == 运算符允许您编写 x == y,这比 x.Equals(y) 更自然,并且将即使 x 为 null 也能工作。

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.

花桑 2024-10-27 16:51:22

重载运算符==只会提高代码的可读性。始终对您定义的类型使用 .Equals(),特别是对于深度对象比较。

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

睫毛上残留的泪 2024-10-27 16:51:22

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文