随着.NET 4.5.3的推出,WPF开发人员现在有三种(或更多)方法来通知属性变化的INotifyPropertyChanged
接口。基本上,我的问题是:“从.NET 4.5开始引入的两种方法中,哪一种方式更有效地通知属性变化,在WPF中使用时是否有任何好处?”
背景
对于那些不太熟悉这个主题的人,这里列出主要的三种方法。第一种是最初的、容易出错的方法,简单地传递一个字符串:
public string TestValue
{
get { return testValue; }
set { testValue = value; NotifyPropertyChanged("TestValue"); }
}
protected virtual void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
第二种方法是在.NET 4.5引入的; CallerMemberNameAttribute
:
public string TestValue
{
get { return testValue; }
set { testValue = value; NotifyPropertyChanged(); }
}
protected virtual void NotifyPropertyChanged([CallerMemberName]string propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
第三种,也是最新的方法将会在C#6.0中作为.NET 4.5.3的一部分引入(或者已经引入);它是nameof
操作符:
public string TestValue
{
get { return testValue; }
set { testValue = value; NotifyPropertyChanged(nameof(TestValue)); }
}
protected virtual void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
我个人的假设是最原始、错误率更高的传递字符串的方法是最有效的,因为我只能想象另外两种方法使用了某种形式的反射。然而,我非常想知道另外两种方法中哪一种更有效,以及在 WPF 上使用 CallerMemberNameAttribute
属性和 nameof
运算符是否会有任何区别。
nameof
是一种语言特性而不是框架的一部分。 - Leonid Vasilev