如何使用equals方法检查不同对象中的字段以查看它们是否相等?

时间:2013-11-18 04:10:05

标签: c# equals gethashcode

如何使用对象equals()和gethashcode()方法检查对象字段值以查看它是否为真?

例如订单号

我启动了几个不同的对象,我需要运行一个equals()方法来检查它们是否等于。

2 个答案:

答案 0 :(得分:0)

使用您自己的实现覆盖Equals()GetHasCode(),然后您不必依赖Object类型的默认实现,您就可以完全控制正在进行的操作上。

答案 1 :(得分:0)

如果您引用的对象是您自己的自定义类,则需要覆盖Equals()GetHashcode()方法。

示例:

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