我看到了 INotifyPropertyChanged 的实现,比如
public event PropertyChangedEventHandler PropertyChanged = delegate { };
我通常这样实现
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
2和推荐使用的有什么区别/优点/缺点?
最佳答案
不同之处在于,通过使用空操作委托(delegate)初始化 PropertyChanged
,您无需担心委托(delegate)是否为 null
因为没有订阅者。
在 C# 6 之前,“检查它是否为 null”方面有点麻烦 - 使用您正在使用的 null 条件运算符,使用它来处理没有订阅者可能更简单。另一种方法仍然有效,您甚至可以将它们一起使用 - 它只是多余的。
关于c# - INotifyPropertyChanged 委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39957670/