如果任何选定的属性值发生更改,请调用另一个方法-C#
我有如果任何选定的属性值发生更改,请调用另一个方法-C#,c#,C#,我有customer类和属性。这是我的示例代码 public class Customer { public string Name { get; set; } public string Deparment { get; set; } public string AccountNo { get; set; } public void UpdateUserProfile(int customerId, string name, string de
customer
类和属性。这是我的示例代码
public class Customer {
public string Name {
get;
set;
}
public string Deparment {
get;
set;
}
public string AccountNo {
get;
set;
}
public void UpdateUserProfile(int customerId, string name, string department, string accountNo) {
bool isNeedUpdateAccount = false;
var customer = _context.Customers.First(c = >c.Id == customerId);
customer.Name = name;
if (department != customer.Deparment) {
customer.Department = department;
isNeedUpdateAccount = true;
}
if (accountNo != customer.AccountNo) {
customer.AccountNo = accountNo;
isNeedUpdateAccount = true;
}
_context.SaveChanges();
//Check is need to update account
if (isNeedUpdateAccount) {
UpdateAccount(customer);
}
}
public void UpdateAccount(Customer model) {
// Do other business logic
}
正如您在这里看到的,我需要检查部门
和帐户编号
值。如果值被更改,那么我将调用另一个方法
如果只得到一个很少的属性
需要检查,就可以了。但是如果我有超过5个,那么让我的代码变长
有什么方法可以使它更简单
如果问题不清楚,请让我知道您案例的问题是,您在每个
If
语句下的UpdateUserProfile
中更新客户。要以更好的方式完成,你需要了解这一点(移动到另一个部分)。然后,您可以使用反射来比较两个对象,但它们将被完全检查。
但要做到这一点,您需要发送到UpdateUserProfile
aCustomer
public void UpdateUserProfile(Customer newCustomer) {
var customer = _context.Customers.First(c = >c.Id == customerId);
var isNeedUpdateAccount = IsDifferent(customer, newCustomer)
if(isNeedUpdateAccount){
//TODO: Update the current Customer
_context.SaveChanges();
}
if (isNeedUpdateAccount) {
UpdateAccount(customer);
}
}
public bool IsDifferent(Customer c1, Customer c2)
{
foreach (PropertyInfo property in c1.GetType().GetProperties())
{
object value1 = property.GetValue(c1, null);
object value2 = property.GetValue(c2, null);
if (!value1.Equals(value2))
{
return true;
}
}
return false;
}
此外,如果返回的是PropertyInfo
列表而不是bool,则可以修改方法IsDifferent
,以返回更改的属性
如果出于任何原因您不想比较整个对象,我建议您编写一个扩展方法来比较所需的几个属性。这是您的类实现的选项吗
INotifyPropertyChanged
?您的代码没有按原样编译。为什么不检查department和accountNo setter。喜欢你可以使用如下。国际会计编号;public int AccountNo{get{return AccountNo;}set{if(value!=AccountNo){//do something}AccountNo=value;}有时只序列化两个对象并检查结果是否不同是很有用的。可能更喜欢二进制序列化,但基于字符串的序列化(如XAML或JSON)也可以