Automated InotifyPropertyChanged Implementation
In the .NET object, the
interface is critical to notify other component attributes. Manually implementing it requires incidents for each attribute, which may be cumbersome. This article discusses the method of simplifying this process. INotifyPropertyChanged
PropertyChanged
Simplifying
A common method is to create a auxiliary method, such as to deal with the model code of the incident:
SetField()
This simplifies the attribute to:
public class Data : INotifyPropertyChanged { // ... protected bool SetField<T>(ref T field, T value, string propertyName) { if (EqualityComparer<T>.Default.Equals(field, value)) return false; field = value; OnPropertyChanged(propertyName); return true; } // 使用SetField()的属性实现 private string name; public string Name { get { return name; } set { SetField(ref name, value, "Name"); } } }
<用> Use C#improvement to enhance
private string name; public string Name { get { return name; } set { SetField(ref name, value); } }
C# 5 introduced attributes, allowing automatic inferring attribute name:
With this enhancement function, you can further simplify the attribute implementation: CallerMemberName
protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null) { // ... }
<> C# 6.0:
set { SetField(ref name, value); }
<> C# 7.0:
protected void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); }
These enhancements have significantly simplified the realization of
protected void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null) { // ... } private string name; public string Name { get => name; set => SetField(ref name, value); }
The above is the detailed content of How Can I Simplify INotifyPropertyChanged Implementation in C#?. For more information, please follow other related articles on the PHP Chinese website!