2009-10-02 14 views
26

Ok、非常にばかげた質問です。void入力のラムダ式

x => x * 2 

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

ためのデリゲートと同じことを表すラムダである。しかし

int Bar() { return 2; } 

のラムダ同等は何ですか?

ありがとうございます!

答えて

36

ヌルラムダ相当物は() => 2となる。

+0

くそ、それは速かった:)ありがとうみんな! – Luk

16

次のようになります。

() => 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

+0

@PussInBootsはいくつかのコメントを追加しました。希望が助けてくれる! –

+0

ありがとうございます。まだ少しFunc xとx()に困惑...私は少し、Func、代理人とlambdasを読む必要があると思う。 – PussInBoots

9

あなたはすることができますパラメータがない場合はuse()を使用してください。

4

lmabdaは次のとおりです。

() => 2