委托是c#很重要的特性。代碼如下:
class Program { public delegate void DelegateTest(); static void Main(string[] args) { DelegateTest dtstatic = new DelegateTest(Program.method1);//實例化,靜態方法,不用new DelegateTest dtinstance = new DelegateTest(new Program().method2);//實例方法,需要new DelegateTest delegatechain = null; //定義為null 的委托鏈 delegatechain += dtinstance;//用 “+”添加委托實例 delegatechain += dtstatic;// delegatechain(); Console.Read(); } private static void method1() { Console.WriteLine("靜態方法輸出"); } private void method2() { Console.WriteLine("實例方法輸出"); } }
運行結果如下:
從結果可以看出委托鏈的執行順序為委托實例的添加順序;
同理,也可用“-”移除委托鏈中的委托實例:
class Program { public delegate void DelegateTest(); static void Main(string[] args) { DelegateTest dtstatic = new DelegateTest(Program.method1);//實例化,靜態方法,不用new DelegateTest dtinstance = new DelegateTest(new Program().method2);//實例方法,需要new DelegateTest delegatechain = null; //定義為null 的委托鏈 delegatechain += dtinstance;//用 “+”添加委托實例 delegatechain += dtstatic; delegatechain -= dtstatic;//用“-”移除委托實例 delegatechain(); Console.Read(); } private static void method1() { Console.WriteLine("靜態方法輸出"); } private void method2() { Console.WriteLine("實例方法輸出"); }
運行結果如下: