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

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

  • 相关阅读:
    [LeetCode#114]Flatten Binary Tree to Linked List
    [LeetCode#103]Binary Tree Zigzag Level Order Traversal
    [LeetCode#102]Binary Tree Level Order Traversal
    [LeetCode#145]Binary Tree Postorder Traversal
    [LeetCode#]Binary Tree Preorder Traversal
    [LeetCode#144]Binary Tree Preorder Traversal
    [LeetCode#94]Binary Tree Inorder Traversal
    [LeetCode#101]Symmetric Tree
    [LeetCode#100]Same Tree
    [LeetCode#104, 111]Maximum Depth of Binary Tree, Minimum Depth of Binary Tree
  • 原文地址:https://www.cnblogs.com/fanmiao/p/4610520.html
Copyright © 2011-2022 走看看