usingSystem;usingSystem.Collections.Generic;usingSystem.Data.SqlClient;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceSrljcshap. Delegate. demo{Delegate voidStringprocessor (stringInput);//declaring delegate types Public classPerson {stringname; PublicPerson (stringName) { This. Name =Name; } //declaring a compatible instance method Public voidSay (stringMSG) {Console.WriteLine ("{0} says: {1}", name, MSG); } } Public classBackground {//declaring a compatible static method Public Static voidNote (stringNote) {Console.WriteLine ("({0})", note); } }}
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Linq;usingSystem.Linq.Expressions;usingSystem.Text;usingSystem.Windows.Forms;namespaceSrljcshap. A lambda expression and an expression tree. demo{classProgram {Static voidMain (string[] args) {Func<string,int>returnlength; Returnlength= Text =text. Length; Console.WriteLine (Returnlength ("Hello")); #regionUse lambda expressions to process a list of moviesvarFilms =NewList<film> { Newfilm{name="Dragon in the lake", year=1999}, Newfilm{name="Violent Neighborhoods", year= .}, Newfilm{name="Western Tour", year=1998}, NewFilm{name="Nanjing Nanjing", year=1985}, NewFilm{name="The Wizard of Oz", year=1935}, NewFilm{name="Apple", year= the} }; Action<Film> print =film= Console.WriteLine ("Name={0},year={1}", Film.name, film.year);//to create a reusable list print delegateFilms. ForEach (print);//Print the original listFilms. FindAll (f= F.year <1990). ForEach (print);//to create a filtered listFilms. Sort ((f1, F2) = F1.name.CompareTo (F2.name));//sort the original listFilms. ForEach (print); #endregion #regionUse a lambda expression to record an eventButton btn=NewButton {Text ="Click Me" }; Btn. Click+ = (src, e) = Log ("Click", SRC, e); Btn. KeyPress+ = (src, e) = Log ("KeyPress", SRC, e); Btn. MouseClick+ = (src, e) = Log ("MouseClick", src,e); Form frm=NewForm {AutoSize =true, Controls ={BTN}}; Application.Run (frm); #endregion #regionA very simple expression treeExpression First= Expression.constant (2); Expression Second= Expression.constant (3); Expression Add=Expression.add (first, second); Console.WriteLine (add); #endregionConsole.readkey (); } Static voidLog (stringTitleObjectsender, EventArgs e) {Console.WriteLine ("event:{0}", title); Console.WriteLine ("sender{0}", sender); Console.WriteLine ("arguments:{0}", E.gettype ()); foreach(PropertyDescriptor propinchtypedescriptor.getproperties (E)) { stringName =Prop. DisplayName; ObjectValue =Prop. GetValue (e); Console.WriteLine ("{0}={1}", name, value); } } }}
C # lambda expressions and expression trees