我最喜欢的 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 -=
所以,我的问题是——我对空传播有什么误解?为什么这不是允许的语法?