// 1 泛型委托--Func Action // 2 Func Action 異步多線程 class Program { static void Main(string[] args) { MyDelegate myDelegate = new MyDelegate(); myDelegate.Show(); Console.ReadKey(); } } class MyDelegate { public void Show() { { //Action Func .NetFramework3.0出現的 //Action和Func 框架預定義的,新的API一律基於這些委托來封裝 //Action 系統提供 0到16個泛型參數 不帶返回值 委托 //Action action = new Action(DoNothing); Action action = DoNothing; //是個語法糖,編譯器幫我們添加上new Action Action<int> action1 = ShowInt; action1(1); Action<int, string, Boolean, DateTime, long, int, string, Boolean, DateTime, long, int, string, Boolean, DateTime, long, string> action16 = null; //Func 系統提供 0到16個泛型參數 帶泛型返回值 委托 //Func 無參數有返回值 Func<int> func = Get; int iResu = func.Invoke(); //Func 有參數有返回值 Func<int, string> func1 = ToString; string sResu = func1.Invoke(1); Func<int, string, Boolean, DateTime, long, int, string, Boolean, DateTime, long, int, string, Boolean, DateTime, long, string, string> func16 = null; } { //多播委托有啥用呢?一個委托實例包含多個方法,可以通過+=/-=去增加/移除方法,Invoke時可以按順序執行全部動作 //多播委托:任何一個委托都是多播委托類型的子類,可以通過+=去添加方法 //+= 給委托的實例添加方法,會形成方法鏈,Invoke時,會按順序執行系列方法 Action method = this.DoNothing; method += Study; method += new MyDelegate().StudyAdvanced; //method.BeginInvoke(null, null);//啟動線程來完成計算 會報錯,多播委托實例不能異步 foreach (Action item in method.GetInvocationList()) { item.Invoke(); item.BeginInvoke(null, null); //異步執行委托 } //method.Invoke(); Console.WriteLine("分割線----------------------------"); //-= 給委托的實例移除方法,從方法鏈的尾部開始匹配,遇到第一個完全吻合的,移除,且只移除一個,如果沒有匹配,就什么也不發生 method -= this.DoNothing; method -= Study; method -= new MyDelegate().StudyAdvanced;//去不掉 原因是不同的實例的相同方法,並不吻合 method.Invoke(); //如果中間出現未捕獲的異常,直接方法鏈結束了 Console.WriteLine("分割線----------------------------"); { Func<int> func = this.Get; func += this.Get2; func += this.Get3; int iResult = func.Invoke(); Console.WriteLine(iResult); //結果是3 以最后一個為准,前面的丟失了。。所以一般多播委托用的是不帶返回值的 } } } public void ShowInt(int i) { Console.WriteLine(i); } public string ToString(int i) { return i.ToString(); } public int Get() { return 1; } public int Get2() { return 2; } public int Get3() { return 3; } public void StudyAdvanced() { Console.WriteLine("StudyAdvanced"); } public void Study() { Console.WriteLine("Study"); } public void DoNothing() { Console.WriteLine("this is DoNothing"); } }