c# - 使用 null 条件运算符和操作

标签 c# c#-6.0

我有以下类(class):

public class MyClass
{
    public Action SomeAction { get; set; }
}

之前当调用 SomeAction 时,因为它有可能为 null 我们会做类似的事情:

var action = SomeAction;
if (action != null)
{
    action();
}

然而,在我们现在有了 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 syntax PropertyChanged?(e). There were too many ambiguous parsing situations to allow it.

关于c# - 使用 null 条件运算符和操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42815314/

相关文章:

c# - 在 C# 中动态创建 Android 控件

c# - 在 Repeater 中填充 DropDownList 不起作用

c# - 模式匹配和占位符值

c# - WebAPI,将一个或集合对象发布到同一操作而不更改消息正文

c# - 远离主要构造函数

c# - 可以对值类型强制执行 [Required]

c# - 使用 roslyn 获取所有类型

c# - Visual Studio 2015 CTP 中没有 C# 6.0?

C# 6.0 功能不适用于 Visual Studio 2015

c# - 一个对象如何同时为 null 和不为 null?