【问题标题】:Is [CallerMemberName] slow compared to alternatives when implementing INotifyPropertyChanged?在实现 INotifyPropertyChanged 时,[CallerMemberName] 与替代方案相比是否慢?
【发布时间】:2014-04-30 02:39:45
【问题描述】:

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

【问题讨论】:

    标签: c# inotifypropertychanged callermembername


    【解决方案1】:

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

    这是因为,根据this MSDN page

    调用者信息值作为文字发送到中间体 编译时的语言 (IL)

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

    所以这里没有使用反射。

    (用VS2013编译的示例)

    【讨论】:

    猜你喜欢
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 2020-07-25
    • 2011-05-12
    • 2018-03-19
    • 1970-01-01
    相关资源
    最近更新 更多