使用继承简化INotifyPropertyChanged接口的实现

  传统使用INotifyPropertyChanged的方式如下:

  

public event PropertyChangedEventHandler PropertyChanged;

private String _Id;
/// <summary>
/// 编号
/// </summary>    
public String Id
{
get { return _Id; }
set
{
_Id = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Id"));
}
}
}

  存在2个问题:

  1.PropertyChanged(this, new PropertyChangedEventArgs("Id"));是硬编码,属于高耦合。

  2.代码太TM繁琐了,写的累死,就是用T4模板生成,这么多看着也累。

  在网上找了下,整理了一下方法,就是利用继承,写一个基类。具体代码

  

 public class PropertyChangedBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

    public static class PropertyChangedBaseEx
    {
        public static void NotifyPropertyChanged<T, TProperty>(this T propertyChangedBase,
          Expression<Func<T, TProperty>> expression) where T : PropertyChangedBase
        {
            var memberExpression = expression.Body as MemberExpression;
            if (memberExpression != null)
            {
                string propertyName = memberExpression.Member.Name;
                propertyChangedBase.NotifyPropertyChanged(propertyName);
            }
            else
                throw new NotImplementedException();
        }
    }

调用方式如下

public class Account : PropertyChangedBase
    {
        private int _Id;
        /// <summary>
        /// 编号
        /// </summary>
        public Int32 Id
        {
            get { return _Id; }
            set { _Id = value; this.NotifyPropertyChanged(p => p.Id); }
        }
    }

这样相对来说个人觉得已经可以了,代码简单,也去掉了硬编码。

原文地址:https://www.cnblogs.com/fanmiao/p/4610520.html