【问题标题】:Conditional Access expression cannot be assigned - C# null-propagation += events无法分配条件访问表达式 - C# null-propagation += events
【发布时间】:2018-01-08 23:03:55
【问题描述】:

我最喜欢的 C# 功能之一是 CS6 中的“null-propagation”。

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

我遇到了一种情况,这似乎是不可能的。我不知道为什么我认为 null 传播只是一些编译器魔术,它为我们做一些 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();
    }

编译输出显示:

 error CS0079: The event 'UIElement.IsMouseDirectlyOverChanged' can only appear on the left hand side of += or -=

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

【问题讨论】:

  • 只能用来阅读;你不能用它来写。因此,expression cannot be assigned。我想一种思考方式是没有设置器的属性。

标签: c# .net c#-6.0 null-propagation-operator


【解决方案1】:

表达式(空传播运算符总是返回)不能用作赋值的左侧部分。

【讨论】:

    【解决方案2】:

    这是设计使然。空传播运算符允许在评估表达式时传播空值,但它不能用作赋值的目标。

    这样想:操作符返回一个。但是,您需要在分配的左侧有一个变量。在那里有一个价值是没有意义的。

    为此打开了issue,目前作为功能请求打开。我们当时得到的回复如下:

    ?.运算符从不产生左值,所以这是设计使然。

    【讨论】:

    猜你喜欢
    • 2014-10-29
    • 1970-01-01
    • 2010-12-07
    • 2017-01-14
    • 2021-05-01
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多