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

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

  • 相关阅读:
    FreeMarker中<#include>和<#import>标签的区别
    freemarker自定义标签(与java合用)
    JSP页面中验证码的调用方法
    js关闭或者刷新页面后执行事件
    动态生成能够局部刷新的验证码【AJAX技术】---看了不懂赔你钱
    Delphi中Indy 10的安装和老版本的卸载
    在Delphi中关于UDP协议的实现
    Easy smart REST with kbmMW
    Delphi事件的广播
    js调用跨域
  • 原文地址:https://www.cnblogs.com/fanmiao/p/4610520.html
Copyright © 2011-2022 走看看