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); }
            }
        }

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

  • 相关阅读:
    Python 学习笔记 11.模块(Module)
    Python 学习笔记 8.引用(Reference)
    Python 学习笔记 9.函数(Function)
    Python 学习笔记 6.List和Tuple
    Python 学习笔记 4.if 表达式
    Python 学习笔记 2.自省
    Python 学习笔记 3.简单类型
    Python 学习笔记 7.Dictionary
    Python 学习笔记 5.对象驻留
    Python 学习笔记 10.类(Class)
  • 原文地址:https://www.cnblogs.com/fanmiao/p/4610520.html
Copyright © 2011-2022 走看看