我必须检查对象属性是否已更改,但只选择它的属性并非全部。像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对象
答案 0 :(得分:1)
我会在您的Equals
课程中覆盖GetHashCode
(+ User
)。然后,如果您还没有这些变量,则从这些变量创建第二个实例,然后您可以编写:if(user1Info.Equals(user2Info)){...}
。如果您不使用代码优先并且您的实体是自动生成的,则可以创建partical 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))
{
}
答案 1 :(得分:0)
尝试这样的事情
public static bool PublicInstancePropertiesEqual<T>(T value, T tobecompared) where T : class
{
if (value!= null && tobecompared!= null)
{
Type type = typeof(T);
foreach (System.Reflection.PropertyInfo pi in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
object selfValue = type.GetProperty(pi.Name).GetValue(self, null);//Get Current value
object toValue = getCompareToValue();
if (selfValue != toValue && (selfValue == null || !selfValue.Equals(toValue)))
{
return false;
}
}
return true;
}
return value == tobecompared;
}