相较于其他实现INotifyPropertyChanged的方法,[CallerMemberName]是否较慢?

114

有一些好的文章建议采用不同的方法来实现 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个回答

227

不,[CallerMemberName] 的使用并不比基本实现更慢。

这是因为根据此MSDN页面的说法:

调用方信息值在编译时作为字面值嵌入到中间语言(IL)中

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

所以这里没有使用反射。

(使用VS2013编译的示例)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接