简体   繁体   English

C# lambda 未命名参数

[英]C# lambda unnamed parameters

is it possible, to discard some arguments in lambda expressions by don't give them a name?是否有可能通过不给它们命名来丢弃 lambda 表达式中的一些参数? Eg I have to pass a Action<int,int>, but I'm only interested in the second param, i want to write something like例如,我必须传递一个 Action<int,int>,但我只对第二个参数感兴趣,我想写类似

(_, foo) => bar(foo)
// or
(, foo) => bar(foo)

In the first case it is working.在第一种情况下它正在工作。 But the first parameter isn't really unnamed, because it has the name "_".但是第一个参数并不是真正未命名的,因为它的名字是“_”。 So it isn't working, when I want to discard two or more.所以当我想丢弃两个或更多时,它不起作用。 I choose _ because in prolog it has the meaning "any value".我选择 _ 因为在序言中它的意思是“任何值”。

So.所以。 Is there any special character or expression for my use case?我的用例是否有任何特殊字符或表达式?

No, you can't.不,你不能。 Looking at the C# language specification grammar, there are two ways to declare lambdas: explicit and implicit.查看C# 语言规范语法,有两种声明 lambdas 的方法:显式和隐式。 Neither one allows you to skip the identifier of the parameter or to reuse identifiers (names).两者都不允许您跳过参数的标识符或重用标识符(名称)。

explicit-anonymous-function-parameter:
  anonymous-function-parameter-modifieropt   type   identifier

implicit-anonymous-function-parameter:
  identifier

It's the same as for unused function parameters in ordinary functions.它与普通函数中未使用的函数参数相同。 They have to be given a name.他们必须被赋予一个名字。

Of course you can use _ as the name for one of the parameters, as it is a valid C# name,当然,您可以使用_作为其中一个参数的名称,因为它是一个有效的 C# 名称, but it doesn't mean anything special.但这并不意味着什么特别的。

As of C# 7, _ does have a special meaning.从 C# 7 开始, _确实具有特殊含义。 Not for lambda expression parameter names but definitely for other things, such as pattern matching, deconstruction, out variables and even regular assignments.不适用于 lambda 表达式参数名称,但肯定用于其他事物,例如模式匹配、解构、out 变量甚至常规赋值。 (For example, you can use _ = 5; without declaring _ .) (例如,您可以使用_ = 5; 而无需声明_ 。)

The short answer is: no, you have to name every parameter, and the names have to be unique.简短的回答是:不,您必须为每个参数命名,并且名称必须是唯一的。

You can use _ as one parameter name because it is a valid identifier in C#.您可以使用_作为一个参数名称,因为它是 C# 中的有效标识符。
However, you can only use it once.但是,您只能使用一次。

Now You Can!现在你可以!

From C# 9.0 onwards, you can use the underscore character to "discard" one or more lambda parameters.从 C# 9.0 开始,您可以使用下划线字符“丢弃”一个或多个lambda 参数。 From Microsoft Docs :来自微软文档

Beginning with C# 9.0, you can use discards to specify two or more input parameters of a lambda expression that aren't used in the expression:从 C# 9.0 开始,您可以使用丢弃来指定表达式中未使用的 lambda 表达式的两个或多个输入参数:

Func<int, int, int> constant = (_, _) => 42;

In C# 7, you can use discards.在 C# 7 中,您可以使用丢弃。 Discards are write only variables which you can not read.丢弃是您无法读取的只写变量。 It is basically for variables that you do not wish to use more details here它基本上适用于您不想在此处使用更多详细信息的变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM