Object.Equals return 错误

Object.Equals return false

Object.Equals总是return假,为什么不相等?

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

克隆方法如下

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

看看这个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.

您的 Student 是引用类型,克隆 MemberwiseClone return 是一个新的其他 object

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

所以 Equal 必须 return false

调用 Clone 时,您创建了一个全新的 class 实例,它具有与原始实例相同的属性和字段。见 MSDN:

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

这两个实例是完全独立的,即使它们在每个 属性 或字段上引用完全相同的值。特别是改变一个属性不会影响另一个。

另一方面,Equals 默认比较两个 引用 是否相等,这在您的情况下显然是错误的。换句话说:仅仅因为你有两个名叫马克的学生并不意味着他们是同一个人。你必须实现平等意味着什么,例如通过比较姓氏或他们的学生身份号码或这些的组合。

您可以在 Student-class 中覆盖 Equals:

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

并使用它:

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