首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在实现INotifyPropertyChanged时,[CallerMemberName]与其他替代方案相比是否很慢?

在实现INotifyPropertyChanged时,[CallerMemberName]与其他替代方案相比是否很慢?
EN

Stack Overflow用户
提问于 2014-03-23 00:55:44
回答 1查看 32.4K关注 0票数 110

有一些很好的文章建议使用different ways for implementing INotifyPropertyChanged

考虑以下基本实现:

代码语言:javascript
复制
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
            }
        }
    }
}

我想用这个来代替它:

代码语言:javascript
复制
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]属性与其他属性相比性能较差。这是真的吗?为什么?它使用反射了吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-23 00:55:44

不,使用 [CallerMemberName] 的速度并不比上层的实现慢。

这是因为,根据this MSDN page的说法,

调用者信息值在编译时作为文字发送到中间语言( Intermediate Language,IL

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

所以这里没有使用反射。

(使用VS2013编译的示例)

票数 222
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22580623

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档