標籤:
using System;using System.Collections.Generic;using System.Data.SqlClient;using System.Linq;using System.Text;using System.Threading.Tasks;namespace SRLJCSHAP.委託.Demo{ delegate void StringProcessor(string input);//聲明委託類型 public class Person { string name; public Person(string Name) { this.name = Name; } //聲明相容的執行個體方法 public void Say(string Msg) { Console.WriteLine("{0} says: {1}", name, Msg); } } public class Background { //聲明相容的靜態方法 public static void Note(string note) { Console.WriteLine("({0})", note); } }}
using System;using System.Collections.Generic;using System.ComponentModel;using System.Linq;using System.Linq.Expressions;using System.Text;using System.Windows.Forms;namespace SRLJCSHAP.Lambda運算式和運算式樹狀架構.Demo{ class Program { static void Main(string[] args) { Func<string, int> returnLength; returnLength = text => text.Length; Console.WriteLine(returnLength("Hello")); #region 用Lambda運算式來處理一個電影列表 var films = new List<Film> { new Film{ name="龍在江湖", year=1999}, new Film{ name="暴力街區",year=2010}, new Film{ name="大話西遊",year=1998}, new Film{name="南京南京",year=1985}, new Film{name="The Wizard OF oz",year=1935}, new Film{name="apple",year=2014} }; Action<Film> print = film => Console.WriteLine("Name={0},year={1}", film.name, film.year);//建立可重用的列表列印委託 films.ForEach(print);//列印原始的列表 films.FindAll(f => f.year < 1990).ForEach(print);//建立篩選過的列表 films.Sort((f1, f2) => f1.name.CompareTo(f2.name));//排序原始列表 films.ForEach(print); #endregion #region 用Lambda運算式來記錄事件 Button btn = new Button { 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 = new Form { AutoSize = true, Controls = { btn } }; Application.Run(frm); #endregion #region 一個非常簡單的運算式樹狀架構 Expression first = Expression.Constant(2); Expression second = Expression.Constant(3); Expression add = Expression.Add(first, second); Console.WriteLine(add); #endregion Console.ReadKey(); } static void Log(string title, object sender, EventArgs e) { Console.WriteLine("Event:{0}", title); Console.WriteLine(" Sender{0}", sender); Console.WriteLine(" Arguments:{0} ", e.GetType()); foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(e)) { string name = prop.DisplayName; object value = prop.GetValue(e); Console.WriteLine("{0}={1}", name, value); } } }}
c# Lambda運算式和運算式樹狀架構