有好文章推荐不同的实施方式INotifyPropertyChanged http://blog.amusedia.com/2013/06/inotifypropertychanged-implementation.html.
考虑以下基本实现:
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]
与替代属性相比,该属性的性能较差。这是真的吗?为什么?它使用反射吗?
No, 指某东西的用途[CallerMemberName]
并不慢比上层基本实现。
这是因为,根据这个 MSDN 页面 https://msdn.microsoft.com/en-us/library/hh534540(v=vs.110).aspx,
调用者信息值作为文字发送到中间
编译时的语言 (IL)
We can check that with any IL disassembler (like ILSpy http://ilspy.net/) : the code for the "SET" operation of the property is compiled exactly the same way :
所以这里没有使用Reflection。
(使用VS2013编译的示例)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)