C# 如何使用equals方法检查不同对象中的字段以查看它们是否相等?
如何使用objects equals()和gethashcode()方法检查对象字段值是否为真 例如订单号C# 如何使用equals方法检查不同对象中的字段以查看它们是否相等?,c#,equals,gethashcode,C#,Equals,Gethashcode,如何使用objects equals()和gethashcode()方法检查对象字段值是否为真 例如订单号 我正在初始化几个不同的对象,我需要运行equals()方法来检查它们是否相等。同时覆盖equals()和GetHasCode()使用您自己的实现,然后您不必依赖对象类型中的默认实现,您可以完全控制正在发生的事情 如果所引用的对象是您自己的自定义类,则需要重写和方法 例如: class Program { static void Main(string[] args) {
我正在初始化几个不同的对象,我需要运行equals()方法来检查它们是否相等。同时覆盖
equals()
和GetHasCode()
使用您自己的实现,然后您不必依赖对象
类型中的默认实现,您可以完全控制正在发生的事情 如果所引用的对象是您自己的自定义类,则需要重写和方法
例如:
class Program
{
static void Main(string[] args)
{
Person p1 = new Person { FirstName = "Manny", Birthday = new DateTime(1970, 1, 4) };
Person p2 = new Person { FirstName = "Moe", Birthday = new DateTime(1970, 1, 4) };
Person p3 = new Person { FirstName = "Manny", Birthday = new DateTime(1970, 1, 4) };
Console.WriteLine("p1 = p2? {0}", p1.Equals(p2));
Console.WriteLine("p2 = p3? {0}", p2.Equals(p3));
Console.WriteLine("p1 = p3? {0}", p1.Equals(p3));
Console.WriteLine("p1 Hash = {0}", p1.GetHashCode());
Console.WriteLine("p2 Hash = {0}", p2.GetHashCode());
Console.WriteLine("p3 Hash = {0}", p3.GetHashCode());
}
}
class Person
{
public string FirstName { get; set; }
public DateTime Birthday { get; set; }
// You define what an equaled object is.
// In this example, we will say a Person is equal if they have the same
// FirstName and Birthday
public override bool Equals(object obj)
{
bool equals = false;
if (obj is Person)
{
Person p = (Person)obj;
if (p.FirstName == this.FirstName && p.Birthday == this.Birthday)
equals = true;
}
return equals;
}
// You define what the hashcode of the object is.
// In this example, we will define the hashcode as the
// concatenation of the FirstName and Birthday
public override int GetHashCode()
{
return string.Format("{0}-{1}", this.FirstName, this.Birthday).GetHashCode();
}
}
程序的输出将是
p1 = p2? False
p2 = p3? False
p1 = p3? True
p1 Hash = 1727998619
p2 Hash = 1625318294
p3 Hash = 1727998619
给我们看看你的代码怎么样