[英]Strange implementation of Object.Equals
I was reading the MSDN documentation about object.Equals
. 我正在阅读有关
object.Equals
的MSDN文档 。 in the remarks part it mentioned: 在评论部分提到:
If the two objects do not represent the same object reference and neither is null, it calls objA.Equals(objB) and returns the result.
如果两个对象不表示相同的对象引用且都不为null,则它调用objA.Equals(objB)并返回结果。 This means that if objA overrides the Object.Equals(Object) method, this override is called.
这意味着如果objA重写Object.Equals(Object)方法,则调用此覆盖。
My question is why they did not implement this part as objA.Equals(objB) && objB.Equals(objA)
to make equality symmetric and just relate on one side of the relation? 我的问题是为什么他们没有将这个部分实现为
objA.Equals(objB) && objB.Equals(objA)
以使等式对称并且只关系到关系的一边? It can result in strange behaviors when calling object.Equals
. 调用
object.Equals
时可能会导致奇怪的行为。
EDIT: Strange behavior can happen when type of objA overrides Equals
method and implemented it as something not predictable, but type of objB does not override Equals
. 编辑:当objA的类型覆盖
Equals
方法并将其实现为不可预测的东西时,可能会发生奇怪的行为,但objB的类型不会覆盖Equals
。
Basically, this would only be of any use to developers with flawed Equals
implementations. 基本上,这只对具有有缺陷的
Equals
实现的开发人员有用。 From the documentation : 从文档 :
The following statements must be true for all implementations of the
Equals(Object)
method.对于
Equals(Object)
方法的所有实现,以下语句必须为true。 In the list,x
,y
, andz
represent object references that are not null.在列表中,
x
,y
和z
表示非空的对象引用。
- [...]
[...]
x.Equals(y)
returns the same value asy.Equals(x)
.x.Equals(y)
返回与y.Equals(x)
相同的值。- [...]
[...]
So the check is redundant in every case where the method has been correctly implemented - causing a performance hit to every developer who has done the right thing. 因此,在正确实施该方法的每种情况下,检查都是多余的 - 对每个做出正确事情的开发人员造成性能损失。
It isn't even terribly useful to developers who haven't done the right thing, as they may still expect object.Equals(x, y)
to return true
when it returns false
- they could debug and find that their method returns true, after all. 它对于没有做正确事情的开发人员来说甚至不是非常有用,因为他们可能仍然期望
object.Equals(x, y)
在返回true
时返回false
- 他们可以调试并发现他们的方法返回true,毕竟。 You could say that it would be documented to check both ways round - but we've already established that the only developers this affects are ones who don't read the documentation anyway. 你可以说它会记录下来检查两种方式 - 但是我们已经确定了影响的唯一开发人员是那些不读文档的人。
Basically, when you override a method or implement an interface, you should know what you're doing and obey the specified contract. 基本上,当您覆盖方法或实现接口时,您应该知道您正在做什么并遵守指定的合同。 If you don't do that, you will get odd behaviour, and I don't think it's reasonable to expect every caller to try to work around implementations which don't do what they're meant to.
如果你不这样做,你会得到奇怪的行为,我不认为期望每个调用者尝试解决那些不符合他们意图的实现是合理的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.