开发者

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


obj1.Equals assumes that obj1 is not null. object.Equals works even on null 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 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.


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).


Be careful to properly implement 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):

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜