Home >Backend Development >C++ >How Can I Simplify INotifyPropertyChanged Implementation in C#?
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:
<code class="language-csharp">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"); } } }</code>
Use C#improvement to enhance
<code class="language-csharp">private string name; public string Name { get { return name; } set { SetField(ref name, value); } }</code>
C# 5 introduced attributes, allowing automatic inferring attribute name:
With this enhancement function, you can further simplify the attribute implementation: CallerMemberName
<code class="language-csharp">protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null) { // ... }</code>The higher version of C#provides more enhancement functions to simplify the implementation:
C# 6.0:
<code class="language-csharp">set { SetField(ref name, value); }</code>
C# 7.0:
<code class="language-csharp">protected void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); }</code>C# 8.0 and can be used for air quotes:
These enhancements have significantly simplified the realization of
<code class="language-csharp">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); }</code>, so that it is no longer a tedious task in the modern version of C#.
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!