[英]What's the difference between obj1.Equals(obj2) and static Object.Equals(obj1, obj2) in c#?
from the documentation by Microsoft, both Equals-methods are essentially the same. 从Microsoft的文档中,两个Equals方法基本相同。 But I just stumbled across something very strange.
但我偶然发现了一些非常奇怪的事情。 in my Silverlight project I have two instances of the same class that overrides Equals.
在我的Silverlight项目中,我有两个同一类的实例覆盖了Equals。 If I ask for inst1.Equals(inst2) or inst2.Equals(inst1) I always get true as result.
如果我要inst1.Equals(INST2)或inst2.Equals(INST1)我总是得到的结果是正确的 。 But Object.Equals(inst1, inst2) returns false .
但是Object.Equals(inst1,inst2)返回false 。 How is this possible?
这怎么可能?
Any Ideas? 有任何想法吗?
Thanks, Rocko 谢谢,Rocko
obj1.Equals
assumes that obj1 is not null
. obj1.Equals
假定obj1不为null
。 object.Equals
works even on null
values. object.Equals
甚至可以在null
值上工作。 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 can be overridden, Object.Equals cannot. 可以覆盖obj1.Equals,Object.Equals不能。 In other words Object.Equals is the base implementation of the Equals method that you get for free if you don't override it.
换句话说,Object.Equals是Equals方法的基本实现,如果不覆盖它,则可以免费获得。 Since you did override it, the two implementations are different and may produce different results.
由于您确实覆盖了它,因此两种实现方式不同,可能会产生不同的结果。
I think that Object.Equals will test if the 2 arguments are the same reference, that is, they point to the same memory space. 我认为Object.Equals将测试2个参数是否是相同的引用,也就是说,它们指向相同的内存空间。
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). MyClass.Equals可能有不同的实现,因此不同参考的2个类实际上可能相等(基于它们的字段和属性)。
Be careful to properly implement IEquatable<T>
. 小心正确实现
IEquatable<T>
。 I did the following mistake: 我做了以下错误:
public class SubjectDTO: IEquatable<SubjectDTO>
{
public string Id;
public bool Equals(SubjectDTO other)
{
return Object.Equals(Id, other.Id);
}
public override int GetHashCode()
{
return Id == null ? 1 : Id.GetHashCode();
}
}
Looks ok, right? 看起来不错吧? But when you try it, you find surprising result:
但是当你尝试它时,你会发现令人惊讶的结果:
var a = new SubjectDTO() { Id = "1"};
var b = new SubjectDTO() { Id = "1"};
Console.WriteLine(Object.Equals(a, b));
Console.WriteLine(a.Equals(b));
False
True
Huh? 咦? Well, it is important to overide
Equals(object other)
: 好吧, 重要的是覆盖
Equals(object other)
:
public override bool Equals(object other)
{
return other == null ? false : Equals(other as SubjectDTO);
}
When you add it to the SubjectDTO
class, it will work as expected. 将它添加到
SubjectDTO
类时,它将按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.