.NET创建基类通知属性基类

定义数值属性基类

    public class NotificateionEntity : INotifyPropertyChanged,INotifyPropertyChanging
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public event PropertyChangingEventHandler PropertyChanging;

        protected void SetWithNotify(T value, ref T field, [CallerMemberName] string propertyName = "")
        {
            if (!Equals(field, value))
            {
                PropertyChanging?.Invoke(this,new PropertyChangingEventArgs(propertyName));
                field = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

继承通知属性

    public class NotifySample : NotificateionEntity
    {
        private int _testValue = 0;

        public int TestValue
        {
            get => _testValue;
            set => SetWithNotify(value, ref _testValue);
        }
    }

使用方法

        static void Main(string[] args)
        {
            var sample = new NotifySample();
            sample.PropertyChanged += SampleOnPropertyChanged;
            while (true)
            {
                var str = Console.ReadLine();
                if (int.TryParse(str, out int val))
                {
                    sample.TestValue = val;
                }
                else
                {
                    Console.Write("请输入数字");
                }
            }
        }

        private static void SampleOnPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            var sample = (NotifySample) sender;
            Console.WriteLine($"属性{e.PropertyName}发生改变,新只为{sample.TestValue}");
        }

你可能感兴趣的:(.NET创建基类通知属性基类)