Null-coalescing运算符和lambda表达式
看看我试图在构造函数中编写的以下代码:
private Predicate _isValid; //... Predicate isValid = //...; this._isValid = isValid ?? s => true;
代码无法编译 – 只是“无效的表达式术语”等等。
相比之下,编译,我可以使用它:
this._isValid = isValid ?? new Predicate(s => true);
但是,我仍然想知道为什么不允许这种语法。
有任何想法吗?
this._isValid = isValid ?? (s => true);
将工作 :)
它以这种方式解析它:
this._isValid = (isValid ?? s) => true;
这没有任何意义。
看看这部分C#语法:
括号内的表达式: (表达) ..... 简单名字: identifier type-argument-listopt ..... 有条件或表达: 条件和表达 条件或表达式|| 条件和表达 空聚结表达: 有条件或表达 条件或表达? 空聚结表达 条件表达式: 空聚结表达 null-coalescing-expression? 表达式:表达式 λ-表达: anonymous-function-signature => anonymous-function-body
由于null-coalescing-expression
以conditional-or-expression
null-coalescing-expression
结尾,因此示例中的s
将解析为simple-name
。 通过将其包装在括号中,然后可以将其解析为带parenthesized-expression
。