zoukankan      html  css  js  c++  java
  • 使用继承简化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); }
            }
        }

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

  • 相关阅读:
    sersync+rsync原理及部署
    rsync同步
    zabbix 3.2.2 agent端(源码包)安装部署
    zabbix配置
    Netbackup media server部署报错
    Oracle_rac命令
    Linux系统克隆为iso镜像盘(类似win gost)
    Nebackup清除磁带数据重新使用
    V7000初始化
    【数据案例】服务器崩溃后的数据恢复方法
  • 原文地址:https://www.cnblogs.com/fanmiao/p/4610520.html
Copyright © 2011-2022 走看看