gpt4 book ai didi

c# - 在实现 INotifyPropertyChanged 时,[CallerMemberName] 是否比替代方案慢?

转载 作者:IT王子 更新时间:2023-10-29 03:37:29 34 4
gpt4 key购买 nike

有好文章推荐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] 属性的性能较差。这是真的吗?为什么?它使用反射吗?

最佳答案

不,使用[CallerMemberName]并不比上面的基本实现慢

这是因为,根据 this MSDN page ,

Caller Info values are emitted as literals into the Intermediate Language (IL) at compile time

我们可以使用任何 IL 反汇编程序(如 ILSpy)进行检查:属性的“SET”操作代码的编译方式完全相同: Decompiled property with CallerMemberName

所以这里没有使用反射。

(使用VS2013编译的示例)

关于c# - 在实现 INotifyPropertyChanged 时,[CallerMemberName] 是否比替代方案慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22580623/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com