我有一个有几十个属性需要引发属性更改事件的类,目前我的代码看起来像
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#中编写这种代码是否有更短的方法,我正在为每个属性进行过多的复制/粘贴操作,我觉得必须有更好的方法.
(这是一个较短的评论,但显然我不允许发布一个,但是.默认情况下,请随意将以下内容降级为评论.)
引用的代码不像编写的那样是线程安全的.请参阅模式以实现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)
| 归档时间: |
|
| 查看次数: |
7851 次 |
| 最近记录: |