简体   繁体   中英

Object.Equals return false

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;
    }

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM