用于触发属性更改事件的更短代码

JME*_*JME 4 c# wpf

我有一个有几十个属性需要引发属性更改事件的类,目前我的代码看起来像

public class Ethernet : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private string timeStamp;

    public string TimeStamp
    {
        get { return timeStamp; }
        set
        {
            timeStamp = value;

            if(PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs("TimeStamp"));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在C#中编写这种代码是否有更短的方法,我正在为每个属性进行过多的复制/粘贴操作,我觉得必须有更好的方法.

dxi*_*xiv 6

(这是一个较短的评论,但显然我不允许发布一个,但是.默认情况下,请随意将以下内容降级为评论.)

引用的代码不像编写的那样是线程安全的.请参阅模式以实现INotifyPropertyChanged?为什么下面的代码更好,以及在接受的答复中链接到Eric Lippert的博客为什么故事不会在那里结束.

    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null) handler(this, new PropertyChangedEventArgs("TimeStamp"));
Run Code Online (Sandbox Code Playgroud)

有关实际问题的答案,请参阅实现INotifyPropertyChanged - 是否存在更好的方法?包括这个C#6.0快捷方式.

    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TimeStamp"));
Run Code Online (Sandbox Code Playgroud)

  • 如果您使用的是C#6,那么最好使用`nameof(TimeStamp)`而不是`TimeStamp`.如果稍后重命名该属性,如果不进行更改,则无法编译. (6认同)
  • @ M.kazemAkhgary - 不,新的c#6.0`.?`是一个空检查代码.当`.``左边的值不是'null`时,它只调用`Invoke`.它编译(在c#6.0中)就好了. (2认同)