如何检查对象是否等于相同类的新对象? [英] How do I check if an object is equal to a new object of the same class?
问题描述
如果我有一个对象,例如:
If I have a object like:
public class Person
{
public int id {get;set;}
public string name {get;set;}
}
我想要的行为是
Person a = new Person();
Person b = new Person();
a == b;
a == b返回true,是否必须重写Object.Equals()方法?还是有其他方法可以执行而不覆盖Equals方法?
and that a == b returns true, do I have to override the Object.Equals() method? or is there some other way of doing it without overriding the Equals method?
EDIT
我想比较数据,因为我想知道我调用的外部方法是否返回一个新对象或具有与新对象不同数据的对象
I want to compare data, as I want to know if a external method that I call returns a new object or a object with different data than a new object
推荐答案
有两种方法可以执行此操作。默认情况下, Equals()
和 ==
检查引用是否相等,即:
There are a couple of ways you can do this. By default Equals()
and ==
check for reference equality, meaning:
Person a = new Person();
Person b = a:
a.Equals(b); //true
a == b; //true
因此,不比较对象的值相等性,这意味着:
And therefore, the objects are not compared for value equality, meaning:
Person a = new Person { id = 1, name = "person1" };
Person b = new Person { id = 1, name = "person1" };
a.Equals(b); //false
a == b; //false
要比较对象的值,您可以覆盖 Equals( )
和 GetHashcode()
方法,例如:
To compare objects for their values you can override the Equals()
and GetHashcode()
methods, like this:
public override bool Equals(System.Object obj)
{
if (obj == null)
return false;
Person p = obj as Person;
if ((System.Object)p == null)
return false;
return (id == p.id) && (name == p.name);
}
public bool Equals(Person p)
{
if ((object)p == null)
return false;
return (id == p.id) && (name == p.name);
}
public override int GetHashCode()
{
return id.GetHashCode() ^ name.GetHashCode();
}
现在,您将在比较时看到其他结果:
Now you will see other results when comparing:
Person a = new Person { id = 1, name = "person1" };
Person b = new Person { id = 1, name = "person1" };
Person c = a;
a == b; //false
a == c; //true
a.Equals(b); //true
a.Equals(c); //true
==
运算符为没有被覆盖,因此仍然进行参考比较。可以通过重载它以及!=
运算符来解决:
The ==
operator is not overridden and therefore still does reference comparison. This can be solved by overloading it as well as the !=
operator:
public static bool operator ==(Person a, Person b)
{
if (System.Object.ReferenceEquals(a, b))
return true;
if ((object)a == null || (object)b == null)
return false;
return a.id == b.id && a.name == b.name;
}
public static bool operator !=(Person a, Person b)
{
return !(a == b);
}
现在运行检查结果如下:
Now running the checks results in following:
Person a = new Person { id = 1, name = "person1" };
Person b = new Person { id = 1, name = "person1" };
Person c = a;
a == b; //true
a == c; //true
a.Equals(b); //true
a.Equals(c); //true
更多阅读内容:
这篇关于如何检查对象是否等于相同类的新对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!