无法分配条件访问表达式 - C#null-propagation + = events

Tra*_*den 7 .net c# c#-6.0 null-propagation-operator

我最喜欢的一个C#功能是CS6中的" 零传播 ".

这为我们许多人清理了很多代码.

我遇到的情况似乎不太可能.我不知道为什么我虽然null传播只是一些编译器魔术,它为我们做了一些空检查,允许我们保持更清晰的代码.

在挂钩事件的情况下..

 public override void OnApplyTemplate()
    {
        _eventStatus = base.GetTemplateChild(PART_EventStatus) as ContentControl;

        // This not permitted and will not compile
        _eventStatus?.IsMouseDirectlyOverChanged += EventStatusOnIsMouseDirectlyOverChanged;

        // but this will work
        if(_eventStatus != null) _eventStatus.IsMouseDirectlyOverChanged += EventStatusOnIsMouseDirectlyOverChanged;

        base.OnApplyTemplate();
    }

    private void EventStatusOnIsMouseDirectlyOverChanged(object sender, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
    {
        throw new NotImplementedException();
    }
Run Code Online (Sandbox Code Playgroud)

编译输出显示:

 error CS0079: The event 'UIElement.IsMouseDirectlyOverChanged' can only appear on the left hand side of += or -=
Run Code Online (Sandbox Code Playgroud)

Resharper投诉

所以,我的问题是 - 我对误传播的误解是什么?为什么这不是允许的语法?

sty*_*ybl 17

这是设计的.空传播运算符允许在计算表达式时传播空值,但不能将其用作赋值的目标.

可以这样想:运算符返回一个.但是,您需要在赋值的左侧使用变量.拥有一个价值是没有意义的.

一个问题被打开过这个问题,是目前作为一个功能要求开放.我们当时得到的答复如下:

?.操作员永远不会产生左值,所以这是设计的.

  • 对于那些仍然感兴趣的人,最近支持了关于此运算符的 C# 功能提案:https://github.com/dotnet/csharplang/issues/2883。看看会不会被捡起来。 (2认同)