Event handler and null-conditional operator [duplicate]

孤人 提交于 2021-01-02 05:38:45

问题


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:

  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:

  1. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!