【发布时间】:2017-11-26 16:46:49
【问题描述】:
假设我有这三个类:
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;
}
现在,如您所见,一个类在继承链中的位置越多,我需要检查的属性就越多。例如,如果我从其他人编写的类继承,我还需要查看类代码以查找其所有属性,因此我可以使用它们来检查值是否相等。对我来说这听起来很奇怪。难道没有更好的方法吗?
【问题讨论】: