下划线箭头(_ => ...)这是什么? [英] Underscore Arrow (_ => ...) What Is This?
问题描述
通俗易懂地阅读C#,我注意到了我从未遇到过的这段代码:
Reading through C# in a Nutshell I noticed this bit of code that I've never came across:
_uiSyncContent.Post(_ => txtMessage.Text += "Test");
下划线后接箭头是什么?我见过Lambda表达式以类似的方式编写,但是没有下划线.
What is that underscore followed by an arrow? I've seen Lambda expressions written in a similar way but nothing with an underscore.
推荐答案
这只是一个使用 _
而不是 x
作为参数的lambda表达式. _
是有效的标识符,因此可以用作参数名称.
It's just a lambda expression that uses _
instead of x
for its parameter. _
is a valid identifier so it can be used as a parameter name.
正如评论中提到的那样,在某些开发人员中是一个惯例,称其为 _
来表示它实际上不是由lambda表达式使用的,但仅此而已:惯例.
As mentioned in the comments, it's a convention among some developers to call it _
to indicate that it's not actually used by the lambda expression, but it's no more than that: a convention.
请注意,这与丢弃(在此答案问世几年后才引入),这是一个特殊变量,用于分配将不使用的值,而将其丢弃.与丢弃的值不同, _
参数在lambda范围内继续存在;在lambda表达式中的任何地方都没有使用它们.而且一次范围内只能有一个 _
.
Note that this is not the same thing as a discard (introduced several years after this answer), which is a special variable for assigning values that aren't going to be used and will instead be discarded. Unlike discarded values, _
parameters continue to exist in lambda scope; they just aren't used anywhere in the lambda expression. And there can only be one _
in scope at a time.
这篇关于下划线箭头(_ => ...)这是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!