2017-06-23 79 views
2

比方说,我有这三类:如何检查所有两个对象的属性是否相等,包括派生的属性?

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; 
} 

现在,你可以看到,更多的一类是沿着继承链中较为我需要检查的属性。例如,如果我从别人编写的类继承,我还需要查看类代码以查找其所有属性,以便我可以使用它们来检查值相等性。这听起来很奇怪。没有更好的方法来做到这一点?

回答

6

使用基地。矮得多。

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

这,也不是原代码,处理情况'其他= null'但其中一个变量,!例如'other.FirstName,== null'。这种情况可能吗? – Gareth

+0

如果'other.FirstName == null','Equals'将返回false,除非'this.FirstName == null'。我认为这是正确的行为。 –

+0

你说得对,当我试图访问一个空对象的变量时,我正在考虑抛出的异常,但'other!= null'对此是一个足够的检查。 – Gareth

1

除了吴宇森的回答,以下是更正后完整的解决方案:

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; 
} 
相关问题