问题
For example, implement INotifyPropertyChanged
interface:
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:
- 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:
- Check it for null, to prevent
NullReferenceException
But now, we can use ?.
operator for null-checking. And if I use it, Resharper is idle:
So, question is: should I copy event ProperyChanged
to local variable, if I use null-conditional operator?
回答1:
should I copy event ProperyChanged to local variable, if I use null-conditional operator?
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)
Why should I check for null before I invoke the custom event?
Raising C# events with an extension method - is it bad?
Is there any reason to assign an event to a local variable before raising it?
回答2:
There is other way for null checking - simple assign delegate{} to your event, so it never be null
public event PropertyChangedEventHandler PropertyChanged = delegate{};
来源:https://stackoverflow.com/questions/37338095/event-handler-and-null-conditional-operator