我最喜欢的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 -=
所以,我的问题是 - 什么,我误解约零传播?为什么这不是一个允许的语法?
您只能用它来阅读;你不能用它来写。因此,“表达不能分配”。我想有一种方法可以想象它是一个没有二传手的财产。 – TyCobb