12

我最喜欢的 C# 特性之一是 CS6 中的“空传播”。

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

我遇到了一种情况,这似乎是不可能的。我不知道为什么我认为空传播只是一些编译器魔术,它为我们做一些空检查,使我们能够维护更干净的代码。

在挂钩事件的情况下..

 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 -=

Resharper 投诉

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

4

2 回答 2

21

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

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

关于此的问题已打开,目前已作为功能请求打开。我们当时得到的回复如下:

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

于 2017-08-01T23:01:44.333 回答
2

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

于 2017-08-01T22:53:14.497 回答