首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在.NET 4.5.3中,使用nameof操作符而不是CallerMemberNameAttribute来通知属性更改有什么好处吗?

在.NET 4.5.3中,使用nameof操作符而不是CallerMemberNameAttribute来通知属性更改有什么好处吗?
EN

Stack Overflow用户
提问于 2015-02-09 01:51:23
回答 2查看 6.4K关注 0票数 23

随着WPF4.5.3的到来,.NET开发人员现在有三种(或更多)方法来通知INotifyPropertyChanged Interface属性更改。基本上,我的问题是,从WPF4.5开始引入的两种方法中,哪一种是更有效的通知属性更改的方式,以及在from.NET中使用这两种方式是否有任何好处?

背景

对于那些不太熟悉这个主题的人,这里有三种主要的方法。第一种是最初的、更容易出错的方法,简单地传递一个字符串:

public string TestValue
{
    get { return testValue; }
    set { testValue = value; NotifyPropertyChanged("TestValue"); }
}

protected virtual void NotifyPropertyChanged(string propertyName)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

第二种方法是在.NET 4.5中引入的;CallerMemberNameAttribute

public string TestValue
{
    get { return testValue; }
    set { testValue = value; NotifyPropertyChanged(); }
}

protected virtual void NotifyPropertyChanged([CallerMemberName]string propertyName = "")
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

第三种也是最新的方法是(或即将)作为.NET 4.5.3的一部分在C#6.0中引入的;nameof Operator

public string TestValue
{
    get { return testValue; }
    set { testValue = value; NotifyPropertyChanged(nameof(TestValue)); }
}

protected virtual void NotifyPropertyChanged(string propertyName)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

我自己的假设是,最初的、更容易出错的简单传递字符串的方法将是最有效的,因为我只能想象其他两种方法使用某种形式的反射。但是,我真的很想知道其他两种方法中哪一种更有效,以及在WPF上下文中使用CallerMemberNameAttribute属性和nameof操作符是否真的有什么不同。

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

https://stackoverflow.com/questions/28397256

复制
相关文章

相似问题

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