简体   繁体   English

Object.Equals返回false

[英]Object.Equals return false

Object.Equals always return false, Why not equal? Object.Equals总是返回false,为什么不等于?

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 看这篇文章 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. 如果当前实例是引用类型,则Equals(Object)方法将测试引用是否相等,并且对Equals(Object)方法的调用等效于对ReferenceEquals方法的调用。 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是一个引用类型,克隆MemberwiseClone返回一个新的其他object

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

So the Equal must return false 因此, Equal必须返回false

When calling Clone you create a completely new instance of your class that has the same properties and fields as the original. 调用Clone您将创建一个类的全新实例,该实例具有与原始类相同的属性和字段。 See MSDN : 参见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. 另一方面,默认情况下, Equals比较两个引用是否相等,在您的情况下显然是错误的。 In other words: only because you have two students named Marc doesn´t mean they are the same person. 换句话说:仅仅因为您有两个名叫Marc的学生并不意味着他们是同一个人。 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: 您可以在Student类中覆盖Equals

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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