2017-08-01 53 views
4

我最喜欢的C#功能之一是CS6中的“null-propagation”。无法分配条件访问表达式 - C#null-propagation + = events

这已经为我们许多人清理了这么多的代码。

我遇到了这种看起来不可能的情况。我不知道为什么,尽管空传播只是一些编译器魔术,它为我们做了一些空的检查,使我们能够保持更清晰的代码。

在挂接到事件的情况下..

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 Complaint

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

+5

您只能用它来阅读;你不能用它来写。因此,“表达不能分配”。我想有一种方法可以想象它是一个没有二传手的财产。 – TyCobb

回答

12

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

想想这样:运营商返回。但是,您需要在作业左侧的变量。有价值就没有意义了。

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

这个?运算符不会产生左值,所以这是设计。

+0

我打算列出这个答案,但它看起来可能在以后的.net版本中有一些希望。这也是一个有趣的答案。 https://stackoverflow.com/questions/32519200/c-sharp-6-0-null-propagation-operator-property-assignment/ – TravisWhidden

+0

这是一个很好的链接订阅,如果任何人有兴趣。 https://github.com/dotnet/csharplang/issues/737 – TravisWhidden

2

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