Object.Equals返回false [英] Object.Equals return false

查看:79
本文介绍了Object.Equals返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Object.Equals总是返回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");
 }

如下所示的克隆方法

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

推荐答案

查看此

如果当前实例是引用类型,则使用Equals(Object)方法测试引用相等性,并调用Equals(Object)方法等效于对ReferenceEquals方法的调用.参考相等意味着所比较的对象变量引用相同的对象.

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 返回一个新的其他 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();

因此,等于必须返回 false

这篇关于Object.Equals返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆