带空输入的Lambda表达式

问题描述:

好吧,非常愚蠢的问题。带空输入的Lambda表达式

x => x * 2 

是代表同样的事情作为

int Foo(x) { return x * 2; } 

但代表一个lambda是什么拉姆达相当于

int Bar() { return 2; } 

的?

非常感谢!

等于零的lambda等于() => 2

+0

该死的,那很快:)谢谢大家! – Luk 2009-10-02 12:37:15

这将是:

() => 2 

用法示例:

var list = new List<int>(Enumerable.Range(0, 10)); 
Func<int> x =() => 2; 
list.ForEach(i => Console.WriteLine(x() * i)); 

正如意见中的要求,这里的上述样品的击穿...

// initialize a list of integers. Enumerable.Range returns 0-9, 
// which is passed to the overloaded List constructor that accepts 
// an IEnumerable<T> 
var list = new List<int>(Enumerable.Range(0, 10)); 

// initialize an expression lambda that returns 2 
Func<int> x =() => 2; 

// using the List.ForEach method, iterate over the integers to write something 
// to the console. 
// Execute the expression lambda by calling x() (which returns 2) 
// and multiply the result by the current integer 
list.ForEach(i => Console.WriteLine(x() * i)); 

// Result: 0,2,4,6,8,10,12,14,16,18 
+0

嗨,这似乎是一个很好的例子;你能用普通的英文一行一行地逐行解释吗? :) – PussInBoots 2013-05-28 09:12:55

+0

@PussInBoots增加了一些评论。希望有所帮助! – 2013-05-28 16:07:45

+0

谢谢。还有一点让Func x和x()感到困惑。我想我需要多读一点Func,代表和lambdas .. – PussInBoots 2013-05-28 19:51:15

你可以只要使用()如果你没有参数。

() => 2; 

的lmabda是:

() => 2