标签:style blog class code java c
怎么说呢 -_-....
委托就是一个存储方法引用的类
很简单也不简单^_^...
废话不多说了,直接上代码,解释都在代码里头了.
1 /* 2 * Created by SharpDevelop. 3 * User: llh 4 * Date: 2014/5/12 5 * Time: 17:31 6 */ 7 using System; 8 9 namespace DelegateTest 10 { 11 class Program 12 { 13 /// <summary> 14 /// 管理算术的委托 15 /// </summary> 16 delegate int MathDel(int a, int b); 17 18 public static void Main(string[] args) 19 { 20 int a = 2, b = 3; 21 22 //简单委托 23 MathDel mathDel = Math.Add; 24 var resu = mathDel(a, b); 25 Console.WriteLine(resu); 26 27 //术语:多播委托 28 //使用下面这种写法,会返回最后一个方法的返回值 29 mathDel += Math.Subtract; 30 resu = mathDel(a, b); 31 Console.WriteLine(resu); 32 33 //委托数组 34 MathDel [] mathDelList = { 35 Math.Add, 36 Math.Subtract 37 }; 38 Console.WriteLine(mathDelList[0](a, b)); 39 40 //绑定匿名方法 41 MathDel mathAnonymous = delegate(int v1, int v2) { 42 return v1 * v2; 43 }; 44 Console.WriteLine(mathAnonymous(a,b)); 45 46 //除了使用自定义委托外 47 //内置了两个委托,使用方法与普通的委托没区别 48 //有返回值(返回值类型为最后一个参数) 49 Func<int,int,int> func = Math.Add; 50 Console.WriteLine(func(a,b)); 51 //无返回值 52 Action<String> action = Math.Pring; 53 Console.Write("Please input your name : "); 54 action(Console.ReadLine()); 55 Console.ReadKey(true); 56 } 57 } 58 59 /// <summary> 60 /// 算术就是它算的 <- 61 /// </summary> 62 public class Math 63 { 64 /// <summary> 65 /// 返回给定参数的和 66 /// </summary> 67 /// <param name="a"></param> 68 /// <param name="b"></param> 69 /// <returns></returns> 70 public static int Add(int a, int b) 71 { 72 return a + b; 73 } 74 /// <summary> 75 /// 返回给定参数的差 76 /// </summary> 77 /// <param name="a"></param> 78 /// <param name="b"></param> 79 /// <returns></returns> 80 public static int Subtract(int a, int b) 81 { 82 return a - b; 83 } 84 85 /// <summary> 86 /// 输出 helloe! + 指定名称 87 /// </summary> 88 /// <param name="param"></param> 89 public static void Pring(String param){ 90 Console.WriteLine("Hello!" + param); 91 } 92 } 93 }
标签:style blog class code java c
原文地址:http://www.cnblogs.com/hualongbei/p/3723938.html