我已经粘贴了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
注意这一行:
actions.Add(()
括号内的()是什么意思?
我已经看过lambda表达式,委托,Action对象的使用等几个例子,但我没有看到这种语法的解释。它有什么作用?为什么需要?
答案 0 :(得分:36)
这是声明不带参数的lambda表达式的简写。
() => 42; // Takes no arguments returns 42
x => 42; // Takes 1 argument and returns 42
(x) => 42; // Identical to above
答案 1 :(得分:6)
这是一个没有参数的lambda表达式。
答案 2 :(得分:5)
我想到这样的lambas:
(x)=&gt; {return x * 2; }
但只有这一点很重要:
( x )=&gt; {return x * 2 ; }
我们需要=&gt;要知道它是一个lambda而不是cast,因此我们得到了这个:
x =&gt; x * 2
(抱歉没有将代码格式化为代码,这是因为你不能在代码中使代码变粗......)
答案 3 :(得分:3)
来自MSDN。表达式lambda采用形式(输入)=&gt;表达式。所以lambda like()=&gt;表达式表示没有输入参数。哪个Action的签名不带参数
答案 4 :(得分:3)
这一行的作用是使用lambda表达式向列表添加匿名Action,它不带参数(这就是()存在的原因)并且不返回任何内容,因为它只打印实际值的柜台。
答案 5 :(得分:2)
它表示没有参数的匿名函数。