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;
}
現在,你可以看到,更多的一類是沿着繼承鏈中較爲我需要檢查的屬性。例如,如果我從別人編寫的類繼承,我還需要查看類代碼以查找其所有屬性,以便我可以使用它們來檢查值相等性。這聽起來很奇怪。沒有更好的方法來做到這一點?
這,也不是原代碼,處理情況'其他= null'但其中一個變量,!例如'other.FirstName,== null'。這種情況可能嗎? – Gareth
如果'other.FirstName == null','Equals'將返回false,除非'this.FirstName == null'。我認爲這是正確的行爲。 –
你說得對,當我試圖訪問一個空對象的變量時,我正在考慮拋出的異常,但'other!= null'對此是一個足夠的檢查。 – Gareth