2017-06-23 77 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; 
} 
相關問題