C# · 12月 31, 2021

c# – 调用INotifyPropertyChanged的PropertyChanged事件的最佳方式是什么?

当您实现INotifyPropertyChanged接口时,您负责在类中更新属性时调用PropertyChanged事件.

这通常导致以下代码:

public class MyClass: INotifyPropertyChanged private bool myfield; public bool MyField { get { return myfield; } set { if (myfield == value) return; myfield = value; OnPropertyChanged(new PropertyChangedEventArgs(“MyField”)); } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(PropertyChangedEventArgs e) { PropertyChangedEventHandler h = PropertyChanged; if (h != null) h(this,e); } }

这是每个财产12行.

如果能够像这样装饰自动属性,将会更简单:

[INotifyProperty]public double MyField{ get; set; }

但不幸的是这是不可能的(例如,见msdn上的this post)

如何减少每个物业所需的代码量?

解决方法 其实,每件物业只有3-4线;其他行通过所有“通知”属性摊销: class Person : INotifyPropertyChanged{ #region INotifyPropertyChanged: Shared bit public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(PropertyChangedEventArgs e) { if (PropertyChanged != null) PropertyChanged(this,e); } #endregion private string _firstName; public string FirstName { get { return _firstName; } set { if (_firstName == value) return; _firstName = value; OnPropertyChanged(new PropertyChangedEventArgs(“FirstName”)); } } // Ditto for other properties}

你可以尝试像下面这样的东西,它们分享一些更多的负载:

private string _firstName;public string FirstName{ get { return _firstName; } set { SetNotifyingProperty(“FirstName”,ref _firstName,value); }}private void SetNotifyingProperty<T>(string propertyName,ref T field,T value){ if (value.Equals(field)) return; field = value; OnPropertyChanged(new PropertyChangedEventArgs(propertyName));}