gpt4 book ai didi

c# - 在 C# 中是否有比较多个属性的快捷方式?

转载 作者:太空宇宙 更新时间:2023-11-03 12:44:04 25 4
gpt4 key购买 nike

我必须检查一个对象的属性是否已经改变,但只是选择它的属性而不是全部。像id,creation_date,……不用勾选

我想知道是否有任何简短的变体可以写这个,我不知道

现在我对每个属性做一个简单的比较:

if (user.first_name != uFirstName || user.last_name != uLastName
|| user.street != uStreet || user.zip_code != uZipCode
|| user.city != uCity || user.country_id != countryAX.id
|| user.email != uEMail || user.phone != uPhone)
{
...
}

“用户”是一个 EntityFramework 对象

最佳答案

我会覆盖 User 类中的 Equals (+GetHashCode)。然后根据这些变量创建第二个实例(如果您还没有的话),您可以编写:if(user1Info.Equals(user2Info)){...}。如果您不使用代码优先并且您的实体是自动生成的,您可以创建一个 partial class User 来实现 Equals

public partial class User
{
public override bool Equals(Object obj)
{
// implement according to your specifications
}

public override int GetHashCode()
{
// implement according to your specifications
}
}

另一种选择是使用自动覆盖 Equals + GetHashCode 的匿名类型:

var user1Info = new 
{
user.first_name,
user.last_name,
user.street, // ...
};
var user2Info = new
{
first_name = uFirstName,
last_name = uLastName,
street = uStreet, // ...
};
if(user1Info.Equals(user2Info))
{

}

关于c# - 在 C# 中是否有比较多个属性的快捷方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37961678/

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