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

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

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

最佳答案

使用基础。短得多。

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

关于c# - 如何检查所有两个对象的属性是否相等,包括派生属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44715765/

相关文章:

java - 重写 equals 方法会出错

java - 覆盖 Hashmap<String,String> 的等于

c# - 如何将工具提示添加到 winform 上的用户定义文本框

c# - 使用 StreamWriter 写入 MemoryStream 返回空

c# - 如何检查 List < int[ ] > 是否包含与另一个 int[ ] 存储相同值的 int[] 元素?

java - 为什么 hashCode() 在遍历具有乘法值的桶时被调用一次?

java - 为什么这两个数组不相等?

c# - .NET WebBrowser 控件 javascript

c# - 键值观察不会在 UIViewController 子类上触发?

java - Equals 和 hashCode 与 EqualsVerifier 的契约(Contract)