InotifyPropertyChanged is the basic interface used in the data binding scenario, so that the class can notify the subscribed component when the attribute is changed. Although Microsoft's implementation involves the PropertyChanged event in each attribute, developers often seek more effective methods. Some people suggest that Microsoft provides a simplified InotifyPropertyChaanged implementation mechanism, similar to automatic attributes. However, this method may bring potential complexity related to inheritance, thread and event subscription.
The customization of the model code to achieve
In the absence of a built -in solution, developers have designed various custom implementations using model code. A common method is to define a base class that contains an event processing program (PropertyChangedEventhandler) and a base class used to cause event. Each attribute is then called onPropertyChanged when setting, and the attribute name is passed as a parameter.
This method needs to write a separate line of code for each attribute, which may become cumbersome and easy to make mistakes, especially in a class with many attributes.
Fortunately, C# has developed to provide the language characteristics of simplifying InotifyPropertyChanged. CallermemberNamettribute allows the attribute to automatically determine its own name. This eliminates the need to pass the attribute name to the onPropertyChanged as a parameter.
In addition, C# 6.0 introduced the empty conditional operator, allowing it to simply call it simply when the PropertyChangeded is not empty. C# 7 further enhances this grammar through the Lambda expression, making the code easier to read. C# 8 and the latest improvement in the higher version
C# 8 introduces a vacuum reference type, allowing more accurate type annotations and safer code. In addition, the grammar of the main member of the expression further simplified the implementation.
In short, although Microsoft did not realize a "fast" InotifyPropertyChanged implementation method, developers have used model code and used C# language characteristics to find creative solutions. These technologies have developed over time, providing more effective and concise methods to achieve this interface that is vital to data binding.
The above is the detailed content of Is There a Better Way to Implement INotifyPropertyChanged in C#?. For more information, please follow other related articles on the PHP Chinese website!