在大多数时候,他们都会写这样的方法:
private void OnPropertyChanged(string prop)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
并将其称为OnPropertyChanged("PropName");
。但这似乎是非常静态的,无法自动重构。有没有办法更动态地做到这一点?我考虑使用System.Diagnostic.StackTrace
类来获取属性的名称,但它看起来很难看并且效率不高,而且我无法访问它,例如Windows Phone 8应用程序(为什么!?)。
答案 0 :(得分:1)
如果您使用的是.NET Framework 4.5,则可以使用[CallerMemberName]
所以你的代码将是:
using System.Runtime.CompilerServices;
class BetterClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
// Check the attribute in the following line :
private void FirePropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
private int sampleIntField;
public int SampleIntProperty
{
get { return sampleIntField; }
set
{
if (value != sampleIntField)
{
sampleIntField = value;
// no "magic string" in the following line :
FirePropertyChanged();
}
}
}
}
如问题INotifyPropertyChanged : is [CallerMemberName] slow compared to alternatives?
中所述答案 1 :(得分:0)
Caliburn.micro有PropertyChangeBase
,允许您使用lambdas。您可以从它继承并调用基本方法。对于属性Name
,您可以执行此操作:
NotifyOfPropertyChange(() => Name);
使用C#6.0,您可以实现自己的基类并使用nameof
运算符,这将有助于重构:
OnPropertyChanged(nameof(Name));