Object.Equals return false

本秂侑毒 提交于 2021-02-17 06:12:12

问题


Object.Equals always return false, Why not equal?

Student student = new Student(3, "Jack Poly");
Student otherStudent = (Student)student.Clone();
if (Object.Equals(student, otherStudent))
{
    Console.WriteLine("Equal");
}
else
 {
    Console.WriteLine("Not Equal");
 }

Clone method like below

    public override StudentPrototype Clone()
    {
        return this.MemberwiseClone() as StudentPrototype;
    }

回答1:


Look at this article MSDN

If the current instance is a reference type, the Equals(Object) method tests for reference equality, and a call to the Equals(Object) method is equivalent to a call to the ReferenceEquals method. Reference equality means that the object variables that are compared refer to the same object.

Your Student is a reference type, The clone MemberwiseClone returns a new other object.

Student student = new Student(3, "Jack Poly");
Student otherStudent = (Student)student.Clone();

So the Equal must return false




回答2:


When calling Clone you create a completely new instance of your class that has the same properties and fields as the original. See MSDN:

Creates a new object that is a copy of the current instance

Both instances are completely independent, even though they reference the exact same values on every single property or field. In particular changing properties from one doesn´t affect the other.

On the other hand Equals by default compares if two references are equal, which obviously is false in your case. In other words: only because you have two students named Marc doesn´t mean they are the same person. You have to implement what equality means, e.g. by comparing the sur-names or their students identity-number or a combination of those.

You can just override Equals in your Student-class:

class Student
{
    public override bool Equals(object other)
    {
        var student = other as Student;
        if(student == null) return false;
        return this.Name == student.Name;
    }
}

and use it:

if (student.Equals(otherStudent)) ...


来源:https://stackoverflow.com/questions/51707331/object-equals-return-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!