2009-10-02 14 views
26

OK, bardzo głupie pytanie.Wyrażenie Lambda z wejściem void

x => x * 2 

jest lambda reprezentujących to samo jako delegat na

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

ale to, co jest równoważne lambda

int Bar() { return 2; } 

??

Wielkie dzięki!

Odpowiedz

36

Nullary odpowiednik lambda będzie () => 2.

+0

Cholera, to było szybko :) Dziękuję wszystkim! – Luk

16

To byłoby:

() => 2 

Przykład użycia:

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

Zgodnie z wnioskiem w komentarzach, oto podział powyższej próbie ...

// 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

Cześć, to wydaje się jak wielki przykład; czy możesz wyjaśnić to po angielsku wiersz po linii, kawałek po kawałku? :) – PussInBoots

+0

@PussInBoots dodał komentarze. Mam nadzieję, że pomaga! –

+0

Dzięki. Wciąż trochę zdziwiony przez Func x i x() .. Myślę, że muszę przeczytać trochę więcej na temat Func, delegatów i lambdas .. – PussInBoots

9

Można po prostu użyj(), jeśli nie masz parametrów.

() => 2; 
4

lmabda jest:

() => 2 
Powiązane problemy