2009-10-02 19 views
26

Ok, domanda molto sciocca.Espressione lambda con immissione nulla

x => x * 2 

è una lambda che rappresenta la stessa cosa di un delegato per

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

Ma qual è il lambda equivalente di

int Bar() { return 2; } 

??

Grazie mille!

risposta

36

L'equivalente lambda nullo sarebbe () => 2.

+0

Dannazione, è stato veloce :) Grazie a tutti! – Luk

16

Che sarebbe: l'utilizzo

() => 2 

Esempio:

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

Come richiesto nei commenti, ecco una ripartizione del campione di cui sopra ...

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

Ciao, questo mi sembra un grande esempio; puoi spiegarlo in inglese semplice riga per riga, pezzo per pezzo? :) – PussInBoots

+0

@PussInBoots ha aggiunto alcuni commenti. Spero possa aiutare! –

+0

Grazie. Ancora un po 'perplesso di Func xe x() .. Penso di aver bisogno di leggere un po' di più su Func, delegati e lambda .. – PussInBoots

9

Puoi usa() se non hai parametri.

() => 2; 
4

Il lmabda è:

() => 2