简体   繁体   English

事件处理程序和空条件运算符

[英]Event handler and null-conditional operator

For example, implement INotifyPropertyChanged interface: 例如,实现INotifyPropertyChanged接口:

public event PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    var handler = PropertyChanged;
    if (handler != null)
        handler.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

Two things: 两件事情:

  1. Copy event to local variable to prevent errors with multithreading ( here are some examples). 将事件复制到本地变量以防止多线程错误( 这里有一些示例)。 Resharper gives notification, if you don't copy to local variable: 如果不复制到局部变量,Resharper会发出通知:

可能的NullReferenceException

  1. Check it for null, to prevent NullReferenceException 检查它是否为null,以防止NullReferenceException

But now, we can use ?. 但现在,我们可以使用?. operator for null-checking. 用于空检查的运算符。 And if I use it, Resharper is idle: 如果我使用它,Resharper是空闲的: 没有错误

So, question is: should I copy event ProperyChanged to local variable, if I use null-conditional operator? 所以,问题是:如果我使用空条件运算符,我应该将事件ProperyChanged复制到局部变量吗?

should I copy event ProperyChanged to local variable, if I use null-conditional operator? 如果我使用空条件运算符,我应该将事件ProperyChanged复制到局部变量吗?

No, there's no need. 不,没有必要。 In fact, one of the main reasons the null-conditional operator was introduced was to simplify code using this pattern. 实际上,引入空条件运算符的主要原因之一是使用此模式简化代码。 It has the same effect as copying the source value to a local variable and inherently avoids the "check and use" concurrency trap that the "copy to local variable" technique is intended to address. 它具有与将源值复制到局部变量相同的效果,并且本质上避免了“复制到本地变量”技术旨在解决的“检查和使用”并发陷阱。

See related posts: 查看相关帖子:
Invoking Events, h(args) vs EventName?.Invoke() (almost an exact duplicate…it does approach the question from a slightly different angle though) 调用事件,h(args)vs EventName?.Invoke() (几乎完全重复......但它确实从稍微不同的角度处理问题)
Why should I check for null before I invoke the custom event? 在调用自定义事件之前,为什么要检查null?
Raising C# events with an extension method - is it bad? 使用扩展方法提升C#事件 - 这很糟糕吗?
Is there any reason to assign an event to a local variable before raising it? 是否有任何理由在提升之前将事件分配给局部变量?

还有其他方法可以进行空检查 - 简单地将委托{}分配给您的事件,因此它永远不会为空

public event PropertyChangedEventHandler PropertyChanged = delegate{};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM