c# - C#中如何检测Property值(ReferenceType属性)是否改变?

标签 c# asp.net-mvc reference-type

我有一个 Customer 类,我希望在用户更改 Customer.CityInfo 属性的值时收到通知。

public class City
{
    public long Id {get;set;}
    public string Code {get;set;}
}

public class Customer
{

    private City cityInfo;
    private string name;

    public long Id { get; set; }
    public bool IsCityModified { get; set;}
    public bool IsCustomerNameModified { get; set; }

    public string Name 
    { 
        get{ return name;} 
        set
        {
           if(name!=value)
           {
              IsCustomerNameModified=true; }name=value;
           } 
        }
     }


    public City CityInfo 
    {
    get
        {
           if(cityInfo==null)
           {
              cityInfo=new City();
           }
           return cityInfo;
         }

      set{
          if(this.cityInfo!=value)
          {
             IsCityModified =true;
          }
          this.cityInfo=value;
       }   
  }
}

public ActionResult Save()
{
    Customer customer=this.currentCustomerSession;
    if(TryUpdateModel<Customer>(customer)){
       UpdateModel<Customer>(customer)
    }
    if(customer.IsCustomerNameModified ){
        //I am able to detect whether the customerName value has been changed in the frontend.
    }
    if(customer.IsCityModified){
        //I am not able to detect whether the city value has been changed in the frontend.
    }
}

如果客户名称自值类型以来发生更改,我可以将标志 (IsCustomerNameModified) 设置为 true。但无法检测到引用类型中所做的更改。

有人可以帮忙吗?

最佳答案

此类问题通常通过更改通知系统来处理。参见这篇文章:How to: Implement Property Change Notification

片段:

  public string PersonName
  {
      get { return name; }
      set
      {
          name = value;
          // Call OnPropertyChanged whenever the property is updated
          OnPropertyChanged("PersonName");
      }
  }

  // Create the OnPropertyChanged method to raise the event 
  protected void OnPropertyChanged(string name)
  {
      PropertyChangedEventHandler handler = PropertyChanged;
      if (handler != null)
      {
          handler(this, new PropertyChangedEventArgs(name));
      }
  }

使用此模式将帮助您避免设置标志或其他此类阴谋。

关于c# - C#中如何检测Property值(ReferenceType属性)是否改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15639700/

相关文章:

c# - 为什么 Object.Equals(new Object(), new Object()) 是假的?

c# - 序列化/反序列化时保留类型信息

typescript - Angular2 使用值等价或引用相等检测变化?

c# - 将数据从字符串值发布到 asp net core web api Controller 方法

c# - 数据结构的 Linq 连接

asp.net-mvc - MVC,是领域的M模型还是有限的和准备好的数据?

asp.net-mvc - 内联如果在Razor View 中

C# 只读对象

c# - 如何为 ASP.NET MVC3 创建全局自定义错误页面?

c# - 如何解决 Autofac 循环依赖?