实现INotifyPropertyChanged时,[CallerMemberName]与替代品相比是否较慢?

时间:2014-03-22 16:55:44

标签: 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]属性与其他选项相比表现不佳。这是真的吗?为什么?它是否使用反射?

1 个答案:

答案 0 :(得分:177)

不,使用[CallerMemberName]并不比上层基本实施慢

这是因为,根据this MSDN page

  

来电者信息值作为文字发布到中级   编译时的语言(IL)

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

所以不要在这里使用反射。

(使用VS2013编译的示例)