空合并运算符和 lambda 表达式

发布于 2024-09-08 21:25:19 字数 389 浏览 1 评论 0原文

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

private Predicate<string> _isValid;

//...

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

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

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

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

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

有什么想法吗?

take a look at the following code I attempted to write inside a constructor:

private Predicate<string> _isValid;

//...

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

The code doesn't compile - just "invalid expression term"s and so one.

In contrast that does compile and I could just use it:

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

However, I still wonder why this syntax is not allowed.

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

留一抹残留的笑 2024-09-15 21:25:19
this._isValid = isValid ?? (s => true);

会起作用的:)

它是这样解析的:

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

这没有任何意义。

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

Will work :)

It parsed it this way:

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

which does not make any sense.

因为看清所以看轻 2024-09-15 21:25:19

查看 C# 语法的这一部分:

parenthesized-expression:
    (   expression   )

.....

simple-name:
    identifier   type-argument-listopt

.....

conditional-or-expression:
    conditional-and-expression
    conditional-or-expression   ||   conditional-and-expression

null-coalescing-expression:
    conditional-or-expression
    conditional-or-expression   ??   null-coalescing-expression

conditional-expression:
    null-coalescing-expression
    null-coalescing-expression   ?   expression   :   expression

lambda-expression:
    anonymous-function-signature   =>   anonymous-function-body

由于 null-coalescing-expressionconditional-or-expression 终止,因此示例中的 s 将解析作为简单名称。通过将其括在括号中,可以将其解析为括号表达式。

Check out this portion of the C# grammar:

parenthesized-expression:
    (   expression   )

.....

simple-name:
    identifier   type-argument-listopt

.....

conditional-or-expression:
    conditional-and-expression
    conditional-or-expression   ||   conditional-and-expression

null-coalescing-expression:
    conditional-or-expression
    conditional-or-expression   ??   null-coalescing-expression

conditional-expression:
    null-coalescing-expression
    null-coalescing-expression   ?   expression   :   expression

lambda-expression:
    anonymous-function-signature   =>   anonymous-function-body

Since null-coalescing-expression terminates with conditional-or-expression the s in your example will parse as a simple-name. By wrapping it in parentheses it can then be parsed as a parenthesized-expression.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文