当实现 INotifyPropertyChanged 时,C# 中的 [NotifyPropertyChangedInvocator] 是什么? [英] What is [NotifyPropertyChangedInvocator] in C# when implements INotifyPropertyChanged?
问题描述
我看到了两种类型的 INotifyPropertyChanged
第一个:
The first one:
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));
}
}
}
第二个:
The second one:
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));
}
}
}
在第二个中,您看到方法 OnPropertyChanged
In 2nd one you see there is an extra attribute [NotifyPropertyChangedInvocator]
on the method OnPropertyChanged
在我的情况下,两者的行为相同,但是什么,为什么以及何时使用此 [NotifyPropertyChangedInvocator]
,这样做有什么好处?我在互联网上搜索过,但找不到任何好的答案.
In my case both behaves same but what, why and when to use this [NotifyPropertyChangedInvocator]
, what are benefits of this? I've searched on internet but couldn't find any good answer.
推荐答案
这是一个 Resharper 属性,来自他们的 注释 - 旨在向您发出警告,然后您的代码看起来很可疑 :)
考虑一下:
It is a Resharper attribute from their Annotations - designed to give you warning then your code looks suspicious :)
Consider this:
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
}
}
}
使用 [NotifyPropertyChangedInvocator]
属性在 NotifyChanged
方法上Resharper 会给你一个警告,你正在调用带有 (大概)错误的值.
因为 Resharper 现在知道应该调用 方法来发出更改通知,它将帮助您将普通属性转换为带有更改通知的属性:
转换成这个:
With the [NotifyPropertyChangedInvocator]
attribut 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:
Converting it into this:
public string Name
{
get { return _name; }
set
{
if (value == _name) return;
_name = value;
NotifyChange("Name");
}
}
此示例来自关于 [NotifyPropertyChangedInvocator]
属性的文档:
This example is from the documentation on the [NotifyPropertyChangedInvocator]
attribute found here:
这篇关于当实现 INotifyPropertyChanged 时,C# 中的 [NotifyPropertyChangedInvocator] 是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!