C# 使用 Actions 时,() 在 lambda 表达式中是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/590756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 09:27:07  来源:igfitidea点击:

What does () mean in a lambda expression when using Actions?

c#lambda

提问by Alex

I have pasted some code from Jon Skeet's C# In Depth site:

我从 Jon Skeet 的 C# In Depth 站点粘贴了一些代码:

static void Main()
{
    // First build a list of actions
    List<Action> actions = new List<Action>();
    for (int counter = 0; counter < 10; counter++)
    {
        actions.Add(() => Console.WriteLine(counter));
    }

    // Then execute them
    foreach (Action action in actions)
    {
        action();
    }
} 

http://csharpindepth.com/Articles/Chapter5/Closures.aspx

http://csharpindepth.com/Articles/Chapter5/Closures.aspx

Notice the line:

注意这一行:

actions.Add( ()

动作.Add(()

What does the () mean inside the brackets?

括号内的 () 是什么意思?

I have seen several examples of lambda expressions, delegates, the use of the Action object, etc but I have seen no explanation of this syntax. What does it do? Why is it needed?

我见过几个 lambda 表达式、委托、Action 对象的使用等示例,但我没有看到对这种语法的解释。它有什么作用?为什么需要它?

采纳答案by JaredPar

This is shorthand for declaring a lambda expression which takes no arguments.

这是声明不带参数的 lambda 表达式的简写。

() => 42;  // Takes no arguments returns 42
x => 42;   // Takes 1 argument and returns 42
(x) => 42; // Identical to above

回答by bruno conde

That's a lambda expression without parameters.

这是一个没有参数的 lambda 表达式。

回答by Ramesh

It denotes anonymous function without a parameter.

它表示没有参数的匿名函数。

回答by JoshBerke

From MSDN. An Expression lambda takes the form (inputs)=>expression. So a lambda like ()=>expression denotes there are no input parameters. Which the signature for Action takes no parameters

来自MSDN。表达式 lambda 采用 (inputs)=>expression 形式。所以像 ()=>expression 这样的 lambda 表示没有输入参数。Action 的签名不带参数

回答by Giuseppe Accaputo

What this line does is to add an anonymous Action to the list using lambda expressions, that takes no parameter (that's the reason why the () are there) and returns nothing, due to the fact that it prints only the actual value of the counter.

这一行的作用是使用 lambda 表达式将一个匿名 Action 添加到列表中,它不接受任何参数(这就是 () 存在的原因)并且不返回任何内容,因为它只打印计数器的实际值.

回答by svinto

I think of lambas like this:

我认为lambas是这样的:

(x) => { return x * 2; }

(x) => { 返回 x * 2; }

But only this is important:

但只有这一点很重要:

(x) => { return x * 2; }

( x) => { 返回x * 2; }

We need the => to know that it's a lambda instead of casting, and thus we get this:

我们需要 => 来知道它是一个 lambda 而不是强制转换,因此我们得到了这个:

x => x * 2

x => x * 2

(sorry for not formatting code as code, that's because you can't make things bold in code..)

(抱歉没有将代码格式化为代码,那是因为你不能在代码中加粗..)