INotifyPropertyChanged的:是[CallerMemberName]相比会更慢的替代品? [英] INotifyPropertyChanged : is [CallerMemberName] slow compared to alternatives?

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

问题描述

有像这个,对实施提出不同的方法 INotifyPropertyChanged的

There are good articles like this one that suggest different ways for implementing INotifyPropertyChanged.

考虑followng基本实现:

Consider the followng basic implementation :

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
            }
        }
    }
}

我想这一个来取代它:

I'd like to replace it with this one :

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

我们可以检查与任何反汇编白细胞介素(如 ILSpy ):在code的属性中的设置操作编译完全相同的方式:

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天全站免登陆