gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:54:01 24 4
gpt4 key购买 nike

假设我有这三个类:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com