How to implement INotifyPropertyChanged in C# 6.0?

后端 未结 3 800
半阙折子戏
半阙折子戏 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

    After incorporating the various changes, the code will look like this. I've highlighted with comments the parts that changed and how each one helps

    public class Data : INotifyPropertyChanged
    { 
        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            //C# 6 null-safe operator. No need to check for event listeners
            //If there are no listeners, this will be a noop
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    
        // C# 5 - CallMemberName means we don't need to pass the property's name
        protected bool SetField(ref T field, T value,
        [CallerMemberName] string propertyName = null)
        {
            if (EqualityComparer.Default.Equals(field, value)) 
                return false;
            field = value;
            OnPropertyChanged(propertyName);
            return true;
        }
    
        private string name;
        public string Name
        {
            get { return name; }
            //C# 5 no need to pass the property name anymore
            set { SetField(ref name, value); }
        }
    }
    

提交回复
热议问题