如何检查是否所有两个对象'属性是否相等,包括派生的属性?

时间:2017-06-23 07:41:32

标签: c# equals

我们说我有这三个类:

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int IdNumber { get; set; }
    public string Address { get; set; }

    // Constructor and methods.
}

class Employee : Person
{
    public byte SalaryPerHour { get; set; }
    public byte HoursPerMonth { get; set; }

    // Constructor and methods.
}

class Seller : Employee
{
    public short SalesGoal { get; set; }
    public bool MetSaleGoleLastYear { get; set; }

    // Constructor and methods.
}

我会像这样实施IEquatable<T>

public bool Equals(Person other)
{
    if (other == null) return false;
    return FirstName == other.FirstName
        && LastName == other.LastName
        && IdNumber == other.IdNumber
        && Address == other.Address;
}

public bool Equals(Employee other)
{
    if (other == null) return false;
    return FirstName == other.FirstName
        && LastName == other.LastName
        && IdNumber == other.IdNumber
        && Address == other.Address
        && SalaryPerHour == other.SalaryPerHour
        && HoursPerMonth == other.HoursPerMonth;
}

public bool Equals(Seller other)
{
    if (other == null) return false;
    return FirstName == other.FirstName
        && LastName == other.LastName
        && IdNumber == other.IdNumber
        && Address == other.Address
        && SalaryPerHour == other.SalaryPerHour
        && HoursPerMonth == other.HoursPerMonth
        && SalesGoal == other.SalesGoal
        && MetSaleGoleLastYear == other.MetSaleGoleLastYear;
}

现在,正如您所看到的,继承链中的类越多,我需要检查的属性就越多。例如,如果我从其他人编写的类继承,我还需要查看类代码以查找其所有属性,因此我可以使用它们来检查值的相等性。这听起来很奇怪。难道没有更好的方法吗?

2 个答案:

答案 0 :(得分:6)

使用基础。更短。

~/.ghci

答案 1 :(得分:1)

除了John Wu的回答,这里还有更正的完整解决方案:

public bool Equals(Person other)
{
    if (other == null) return false;
    return FirstName == other.FirstName
        && LastName == other.LastName
        && IdNumber == other.IdNumber
        && Address == other.Address;
}

public bool Equals(Employee other)
{
    if (other == null) return false;
    return base.Equals(other)
        && SalaryPerHour == other.SalaryPerHour // ; removed
        && HoursPerMonth == other.HoursPerMonth;
}

public bool Equals(Seller other)
{
    if (other == null) return false;
    return base.Equals(other)
        && SalesGoal == other.SalesGoal // SalaryPerHour;
        && MetSaleGoleLastYear == other.MetSaleGoleLastYear; //HoursPerMonth;
}