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

标签 c# inotifypropertychanged callermembername

有好文章推荐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/

相关文章:

c# - 一个无法访问的类。 VS2010

c# - 如何将数据绑定(bind)到密封类?

wpf - WCF 到 WPF 类 INotifyPropertyChanged 怎么样

c# - CallerMemberName 不适用于字段上的属性构造函数

c# - 覆盖 GetEnumerator 的默认行为

c# - 是否存在一种 C# 哈希生成方法,其中值的顺序无关紧要?

c# - asp.net mvc Razor 额外空间

c# - 在使用 HTTPS 443 绑定(bind)托管的 WCF 服务中获取客户端 IP 地址

wpf - 子类中的 INotifyPropertyChanged