gpt4 book ai didi

c# - Object.Equals 的奇怪实现

转载 作者:IT王子 更新时间:2023-10-29 04:29:12 24 4
gpt4 key购买 nike

我正在阅读 MSDN documentation about object.Equals .在评论部分提到:

If the two objects do not represent the same object reference and neither is null, it calls objA.Equals(objB) and returns the result. This means that if objA overrides the Object.Equals(Object) method, this override is called.

我的问题是,为什么他们没有将这部分实现为 objA.Equals(objB) && objB.Equals(objA) 来使等式对称并且只在关系的一侧相关?调用 object.Equals 时可能会导致奇怪的行为。

编辑: 当 objA 的类型覆盖 Equals 方法并将其实现为不可预测的东西时,可能会发生奇怪的行为,但 objB 的类型不会覆盖 Equals.

最佳答案

基本上,这只会对有缺陷的 Equals 实现的开发人员有用。来自documentation :

The following statements must be true for all implementations of the Equals(Object) method. In the list, x, y, and z represent object references that are not null.

  • [...]
  • x.Equals(y) returns the same value as y.Equals(x).
  • [...]

因此,在方法已正确实现的每种情况下,检查都是多余的 - 会对每个做正确事情的开发人员造成性能影响。

对于没有做正确事情的开发人员来说,它甚至不是非常有用,因为他们可能仍然期望 object.Equals(x, y) 返回true 当它返回 false - 他们可以调试并发现 他们的 方法毕竟返回 true。您可以说会记录双向检查 - 但我们已经确定,受此影响的唯一开发人员是那些根本不阅读文档的开发人员。

基本上,当你覆盖一个方法或实现一个接口(interface)时,你应该知道你在做什么并遵守指定的契约。如果你不这样做,你得到奇怪的行为,而且我认为期望每个调用者尝试绕过不做他们想要的实现的实现是不合理的.

关于c# - Object.Equals 的奇怪实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31645536/

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