美文网首页
.NET创建基类通知属性基类

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

作者: Aweber | 来源:发表于2018-09-08 17:30 被阅读0次

    定义数值属性基类

        public class NotificateionEntity : INotifyPropertyChanged,INotifyPropertyChanging
        {
            public event PropertyChangedEventHandler PropertyChanged;
            public event PropertyChangingEventHandler PropertyChanging;
    
            protected void SetWithNotify<T>(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创建基类通知属性基类

          本文链接:https://www.haomeiwen.com/subject/rvhlgftx.html