最佳答案
有好的文章建议 实现 INotifyPropertyChanged
的不同方法。
考虑下列基本实施办法:
class BasicClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void FirePropertyChanged(string propertyName)
{
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;
FirePropertyChanged("SampleIntProperty"); // ouch ! magic string here
}
}
}
}
我想把它换成这个:
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();
}
}
}
}
但是有时我读到 [CallerMemberName]
属性与其他属性相比性能较差。是真的吗,为什么?它使用反射吗?