与实现INotifyPropertyChanged时的替代方法相比,[CallerMemberName]是否较慢? [英] Is [CallerMemberName] slow compared to alternatives when implementing INotifyPropertyChanged?

查看:115
本文介绍了与实现INotifyPropertyChanged时的替代方法相比,[CallerMemberName]是否较慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好文章建议实现的不同方法INotifyPropertyChanged

There are good articles that suggest 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] 属性与替代方法相比性能较差。那是真的,为什么?

But sometimes I read that the [CallerMemberName] attribute has poor performances compared to alternatives. Is that true and why? Does it use reflection?

推荐答案

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

No, the use of [CallerMemberName] is not slower than the upper basic implementation.

这是因为,根据此MSDN页面


呼叫者信息值在编译时作为文字发送到中间
语言(IL)

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

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

We can check that with any IL disassembler (like ILSpy) : the code for the "SET" operation of the property is compiled exactly the same way :

因此在这里不使用反射。

So no use of Reflection here.

(使用VS2013编译的示例)

(sample compiled with VS2013)

这篇关于与实现INotifyPropertyChanged时的替代方法相比,[CallerMemberName]是否较慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆