gpt4 book ai didi

C# 对象比较

转载 作者:行者123 更新时间:2023-11-30 20:10:21 26 4
gpt4 key购买 nike

有人可以指出重载 operator== 以执行深度对象比较(而不是引用比较)的想法。

来自 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.

它什么时候真正受益?

而且,如果每个对象都有方法 Equals,这使得值比较成为可能,为什么有人会执行 value (不是引用) 使用 x == y 语句进行比较?

我想我不明白什么,因为这对我来说看起来很奇怪。

最佳答案

重载== 运算符允许您编写x == y,这比x.Equals(y) 自然得多, 即使 x 为 null 也能正常工作。

关于C# 对象比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5212039/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com