【问题标题】:Null-coalescing operator and lambda expression空合并运算符和 lambda 表达式
【发布时间】:2011-03-14 04:28:42
【问题描述】:

看看我尝试在构造函数中编写的以下代码:

private Predicate<string> _isValid;

//...

Predicate<string> isValid = //...;
this._isValid = isValid ?? s => true;

代码无法编译 - 只是“无效的表达式术语”等等。

相比之下,它确实可以编译,我可以使用它:

this._isValid = isValid ?? new Predicate<string>(s => true);

但是,我仍然想知道为什么不允许使用这种语法。

有什么想法吗?

【问题讨论】:

    标签: c# .net lambda null-coalescing-operator


    【解决方案1】:

    查看这部分 C# 语法:

    括号表达式: ( 表达 ) ...... 简单名称: 标识符类型参数列表选择 ...... 条件或表达式: 条件表达式 条件或表达式 ||条件表达式 空合并表达式: 条件或表达式 条件或表达式??空合并表达式 条件表达式: 空合并表达式 空合并表达式?表达:表达 lambda 表达式: 匿名函数签名 => 匿名函数体

    由于null-coalescing-expressionconditional-or-expression 终止,因此您示例中的s 将解析为simple-name。通过将其包裹在括号中,它可以被解析为parenthesized-expression

    【讨论】:

      【解决方案2】:
      this._isValid = isValid ?? (s => true);
      

      会工作:)

      它是这样解析的:

      this._isValid = (isValid ?? s) => true;
      

      这没有任何意义。

      【讨论】:

        猜你喜欢
        • 2012-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-23
        相关资源
        最近更新 更多