首先定义两个委托和几个方法,后面会用到。
委托:
1 public delegate void M1Delegate(); 2 3 public delegate int M2Delegate(int x,int y);
方法:
1 static int A1(int x,int y) 2 { 3 return x + y; 4 } 5 6 static int A2(int x, int y) 7 { 8 return x + y; 9 } 10 11 static int A3(int x, int y) 12 { 13 return x + y; 14 } 15 16 static void M1() { 17 Console.WriteLine("这是M1方法"); 18 } 19 20 static void M2() 21 { 22 Console.WriteLine("这是M2方法"); 23 } 24 25 static void M3() 26 { 27 Console.WriteLine("这是M3方法"); 28 } 29 30 static void M4() 31 { 32 Console.WriteLine("这是M4方法"); 33 } 34 35 36 static int N1(int x, int y) 37 { 38 return 10; 39 } 40 41 static int N2(int x, int y) 42 { 43 return 20; 44 } 45 46 static int N3(int x, int y) 47 { 48 return 30; 49 }
一、如何实现多播委托
1 M1Delegate m1 = M1; 2 m1 += M2; 3 m1 += M3; 4 m1 += M4; 5 6 m1 -= M1; 7 m1();
二、多播委托的实现过程(反编译后的源码)
1 M1Delegate m1 = new M1Delegate(M1); 2 m1 = (M1Delegate)Delegate.Combine(m1, new M1Delegate(M2)); 3 m1 = (M1Delegate)Delegate.Combine(m1, new M1Delegate(M3)); 4 m1 = (M1Delegate)Delegate.Combine(m1, new M1Delegate(M4)); 5 m1 = (M1Delegate)Delegate.Remove(m1, new M1Delegate(M2)); 6 m1();
输出M1,M3,M4。注意里面的remove方法,我们是新创建了一个委托变量,再删除原来的委托,这点不好理解,反编译后也无法查看原因,暂时记住。
三、多播委托的返回值
1 //这里,多播委托只能取到最后一次方法的值 2 M2Delegate m1 = A1; 3 m1 += A2; 4 m1 += A3; 5 int n = m1(100, 200); 6 Console.WriteLine(n);
输出300;
1 M2Delegate m1 = A1; 2 m1 += N1; 3 m1 += N2; 4 m1 += N3; 5 int n = m1(100, 200); 6 Console.WriteLine(n);//这里,多播委托只能取到最后一次方法的值
输出30;
以上例子说明,多播委托只能取到最后调用的那个方法的返回值,那能否取到多播委托中的所有方法的返回值呢?
1 //如果让多播委托返回每个方法的值呢? 2 M2Delegate m1 = A1; 3 m1 += A1; 4 m1 += A2; 5 m1 += A3; 6 Delegate[] dList = m1.GetInvocationList(); 7 8 foreach (var item in dList) 9 { 10 int n = ((M2Delegate)item)(11, 22); 11 Console.WriteLine(n); 12 }
时间: 2024-10-27 06:34:49