C# 委托链(多播委托)
委托既可以封装一个方法,又可以对同一类型的方法进行封装,它就是多播委托
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace DelegateTest 7 { 8 class Program 9 { 10 //申明一个委托类型,它的实例引用一个方法 11 //该方法传递0参数,返回void类型 12 public delegate string DelegateTestOne(); 13 14 static void Main(string[] args) 15 { 16 //用静态方法来实例化委托 17 DelegateTestOne teststatic = new DelegateTestOne(Program.method1); 18 19 //用实例方法来实例化委托 20 DelegateTestOne test2 = new DelegateTestOne(new Program().method2); 21 22 //用实例方法来实例化委托 23 DelegateTestOne test3 = new DelegateTestOne(new Program().method3); 24 25 //定义空一个委托对象 26 DelegateTestOne deleteAll = null; 27 deleteAll += teststatic; 28 deleteAll += test2; 29 deleteAll += test3; 30 Console.WriteLine(Test(deleteAll)); 31 32 Console.ReadLine(); 33 } 34 35 36 public static string method1() 37 { 38 39 //Console.WriteLine("这是一个静态方法"); 40 return "这是一个静态方法"; 41 } 42 43 public string method2() 44 { 45 //Console.WriteLine("这是实例方法2"); 46 return "这是实例方法2"; 47 } 48 49 public string method3() 50 { 51 // Console.WriteLine("这是实例方法3"); 52 return "这是实例方法3"; 53 } 54 55 56 //测试多播委托 57 public static string Test(DelegateTestOne testone) 58 { 59 if (testone == null) 60 { 61 return null; 62 } 63 StringBuilder returnstring = new StringBuilder(); 64 65 Delegate[] delegatearray = testone.GetInvocationList(); 66 67 foreach (DelegateTestOne t in delegatearray) 68 { 69 try 70 { 71 returnstring.Append(t() + Environment.NewLine); 72 } 73 catch (Exception e) 74 { 75 76 } 77 } 78 //把结果返回给调用者 79 return returnstring.ToString(); 80 } 81 82 } 83 }
运行结果:
JUST DO IT