我有以下类(class):
public class MyClass
{
public Action SomeAction { get; set; }
}
之前c#-6.0当调用 SomeAction
时,因为它有可能为 null
我们会做类似的事情:
var action = SomeAction;
if (action != null)
{
action();
}
然而,在c#-6.0我们现在有了 null 条件运算符,所以可以将上面的代码写成:
SomeAction?.Invoke();
但是,由于 Invoke
调用,我发现它的可读性稍差。在没有 Invoke
调用的情况下,是否可以在这种情况下使用 null 条件运算符?像这样的东西:
SomeAction?();
最佳答案
不,C# 6.0 或 7.0 中没有这样的语法。 The null conditional operator有两种口味:
- null-condition member access
?.
,你已经拒绝了,因为它太冗长了 - null-condition index
?[
,这对委托(delegate)没有意义(并且不能作为扩展添加,或类似的东西)
文档甚至直接提到了这一点:
You need to explicitly call the
Invoke
method because there is no null-conditional delegate invocation syntaxPropertyChanged?(e)
. There were too many ambiguous parsing situations to allow it.
关于c# - 使用 null 条件运算符和操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42815314/