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)
所以,我的问题是 - 我对误传播的误解是什么?为什么这不是允许的语法?