当实现 INotifyPropertyChanged 时,C# 中的 [NotifyPropertyChangedInvocator] 是什么?

2023-12-27

我看到两种类型的实现INotifyPropertyChanged

  • 第一个:

    public abstract class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
    
  • 第二个:

    public abstract class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    
        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
    

在第二个中你会看到有一个额外的属性[NotifyPropertyChangedInvocator]关于方法OnPropertyChanged

就我而言,两者的行为相同,但是什么、为什么以及何时使用它[NotifyPropertyChangedInvocator],这样做有什么好处?我在互联网上搜索过但找不到任何好的答案。


这是他们的 Resharper 属性注释 https://www.jetbrains.com/help/resharper/Code_Analysis__Code_Annotations.html- 旨在向您发出警告,然后您的代码看起来很可疑:)
考虑一下:

public class Foo : INotifyPropertyChanged 
{
     public event PropertyChangedEventHandler PropertyChanged;
     
     [NotifyPropertyChangedInvocator]
     protected virtual void NotifyChanged(string propertyName) { ... }
  
     private string _name;
     public string Name {
       get { return _name; }
       set { 
             _name = value; 
             NotifyChanged("LastName");//<-- warning here
           } 
     }
   }

With the [NotifyPropertyChangedInvocator] attribute on the NotifyChanged method Resharper will give you a warning, that you are invoking the method with a (presumably) wrong value.

Because Resharper now knows that method should be called to make change notification, it will help you convert normal properties into properties with change notification: Visual Studio Screenshot showing ReShaper suggestions
Converting it into this:

public string Name
{
  get { return _name; }
  set
  {
    if (value == _name) return;
    _name = value;
    NotifyChange("Name");
  }
}



This example is from the documentation on the [NotifyPropertyChangedInvocator] attribute found here:
enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当实现 INotifyPropertyChanged 时,C# 中的 [NotifyPropertyChangedInvocator] 是什么? 的相关文章

随机推荐