C# 中 obj1.Equals(obj2) 和 static Object.Equals(obj1, obj2) 有什么区别?
从微软的文档来看,两种 Equals 方法本质上是相同的。但我偶然发现了一些非常奇怪的事情。 在我的 Silverlight 项目中,我有两个覆盖 Equals 的同一类实例。 如果我要求 inst1.Equals(inst2) 或 inst2.Equals(inst1) 我总是得到 true 结果。但Object.Equals(inst1, inst2)返回false。这怎么可能?
有什么想法吗?
谢谢, 洛科
from the documentation by Microsoft, both Equals-methods are essentially the same. But I just stumbled across something very strange.
in my Silverlight project I have two instances of the same class that overrides Equals.
If I ask for inst1.Equals(inst2) or inst2.Equals(inst1) I always get true as result. But Object.Equals(inst1, inst2) returns false. How is this possible?
Any Ideas?
Thanks,
Rocko
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
obj1.Equals
假定 obj1 不为null
。object.Equals
甚至适用于null
值。但这并不能解释你所看到的行为;我认为您应该提供一些代码来重现它以获得更好的答案。obj1.Equals
assumes that obj1 is notnull
.object.Equals
works even onnull
values. That doesn't explain the behavior you see though; I think you should provide some code to reproduce it for a better answer.obj1.Equals 可以被覆盖,Object.Equals 不能。换句话说,Object.Equals 是 Equals 方法的基本实现,如果您不重写它,则可以免费获得它。由于您确实覆盖了它,因此这两种实现是不同的,并且可能会产生不同的结果。
obj1.Equals can be overridden, Object.Equals cannot. In other words Object.Equals is the base implementation of the Equals method that you get for free if you don't override it. Since you did override it, the two implementations are different and may produce different results.
我认为 Object.Equals 将测试两个参数是否是相同的引用,即它们指向相同的内存空间。
MyClass.Equals 可能有不同的实现,这样两个不同引用的类实际上可能是相等的(基于它们的字段和属性)。
I think that Object.Equals will test if the 2 arguments are the same reference, that is, they point to the same memory space.
MyClass.Equals may have a different implementation, such that 2 classes that aren't the same reference may in fact be equal (based on their fields and properties).
请小心正确实现
IEquatable
。我犯了以下错误:看起来不错,对吧?但当你尝试时,你会发现令人惊讶的结果:
啊?嗯,覆盖
Equals(object other)
非常重要:当您将其添加到
SubjectDTO
类时,它将按预期工作。Be careful to properly implement
IEquatable<T>
. I did the following mistake:Looks ok, right? But when you try it, you find surprising result:
Huh? Well, it is important to overide
Equals(object other)
:When you add it to the
SubjectDTO
class, it will work as expected.