如何用nameof而不是魔术字符串实现INotifyPropertyChanged?

Meh*_*rad 7 c# mvvm inotifypropertychanged c#-6.0

我正在阅读nameofC#6中关于new 关键字的内容.我想知道如何INotifyPropertyChanged使用此关键字实现,前提条件(当然除了C#6之外)以及它将如何影响我的MVVM应用程序的性能?

Wim*_*nen 10

它看起来像这样:

public string Foo
{
   get
   {
      return this.foo;
   }
   set
   {
       if (value != this.foo)
       {
          this.foo = value;
          OnPropertyChanged(nameof(Foo));
       }
   }
}
Run Code Online (Sandbox Code Playgroud)

nameof(Foo)会在编译时的"富"的字符串替换,所以它应该是非常高性能的.这不是反思.

  • `CallerMemberName`仅适用于.NET 4.5.`Nameof`附带C#编译器,因此您仍然可以定位较旧的.NET框架. (2认同)

Gig*_*igi 6

这只是使用nameof()而不是魔术字符串的问题.以下示例来自我关于此主题的博客文章:

private string currentTime;

public string CurrentTime
{
    get
    {
        return this.currentTime;
    }
    set
    {
        this.currentTime = value;
        this.OnPropertyChanged(nameof(CurrentTime));
    }
}
Run Code Online (Sandbox Code Playgroud)

由于它是在编译时进行评估的,因此它比任何当前的替代方案(在博客文章中也提到)更具性能.