How to implement INotifyPropertyChanged in C# 6.0?

后端 未结 3 806
半阙折子戏
半阙折子戏 2020-11-29 08:36

The answer to this question has been edited to say that in C# 6.0, INotifyPropertyChanged can be implemented with the following OnPropertyChanged procedure:

         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 08:56

    I know this question is old, but here is my implementation

    Bindable uses a dictionary as a property store. It's easy enough to add the necessary overloads for a subclass to manage its own backing field using ref parameters.

    • No magic string
    • No reflection
    • Can be improved to suppress the default dictionary lookup

    The code:

        public class Bindable : INotifyPropertyChanged
        {
            private Dictionary _properties = new Dictionary();
    
            /// 
            /// Gets the value of a property
            /// 
            /// 
            /// 
            protected T Get([CallerMemberName] string name = null)
            {
                object value = null;
                if (_properties.TryGetValue(name, out value))
                    return value == null ? default(T) : (T)value;
                return default(T);
            }
    
            /// 
            /// Sets the value of a property
            /// 
            /// 
            /// 
            /// 
            protected void Set(T value, [CallerMemberName] string name = null)
            {
                if (Equals(value, Get(name)))
                    return;
                _properties[name] = value;
                OnPropertyChanged(name);
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    

    used like this

    public class Item : Bindable
    {
         public Guid Id { get { return Get(); } set { Set(value); } }
    }
    

提交回复
热议问题