Can I use null conditional operator instead of cla

2020-02-07 01:12发布

问题:

C# 6.0 adds this new ?. operator which now allows to invoke events like so:

someEvent?.Invoke(sender, args);

Now, from what I read, this operator guarantees that someEvent is evaluated once. Is it correct to use this kind of invocation instead of the classic pattern:

var copy = someEvent

if(copy != null)
  copy(sender, args)

I'm aware of certain scenarios where above version of pattern would require additional locks, but let's assume the simplest case.

回答1:

Yes

See Null-conditional Operators on MSDN.

There is an example covering what you ask

Without the null conditional operator

var handler = this.PropertyChanged;
if (handler != null)
    handler(…)

With the null conditional operator

PropertyChanged?.Invoke(e)

The new way is thread-safe because the compiler generates code to evaluate PropertyChanged one time only, keeping the result in temporary variable.