有一些很好的文章建议使用different ways for implementing 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]
属性与其他属性相比性能较差。这是真的吗?为什么?它使用反射了吗?
发布于 2014-03-23 00:55:44
不,使用 [CallerMemberName]
的速度并不比上层的实现慢。
这是因为,根据this MSDN page的说法,
调用者信息值在编译时作为文字发送到中间语言( Intermediate Language,IL
我们可以使用任何IL反汇编程序(如ILSpy)来检查:属性的"SET“操作的代码是以完全相同的方式编译的:
所以这里没有使用反射。
(使用VS2013编译的示例)
https://stackoverflow.com/questions/22580623
复制相似问题