View Code
1 using System; 2 3 // 声名一个代理,与类同级(其本质就是类) 4 delegate void theHandler(int i); 5 6 class TestClass 7 { 8 public void plus(int i) { 9 Console.WriteLine( " i + i = " + (i + i).ToString()); 10 } 11 // 这个方法中的第一个参数 是一个代理. 12 // 我们可以直接传入一个与其签名相同的 方法名. 13 public void delegateMethod(theHandler del,int i) { 14 del(i); 15 } 16 17 18 } 19 20 21 class Program 22 { 23 // 事件声名要在方法体的外部,其本质为代理的实例 24 static event theHandler thEvent; 25 26 static void Main(string[] args) 27 { 28 if (args.Length == 1) { 29 TestClass tc = new TestClass(); 30 // 直接装 签名相同的方法 传到 这个代理的位置 31 tc.delegateMethod(tc.plus,int.Parse(args[0])); 32 // 使用事件(代理的实例) 33 // 直接实例化代理, 必须传入一个同签名方法,不然编译出错 34 // 而声名一个事件时可以不传同签名方法. 35 //theHandler th = new theHandler(); 36 // 将同签名的方法直接附值给 事件. 37 thEvent = tc.plus; 38 tc.delegateMethod(thEvent,int.Parse(args[0])); 39 } else { 40 Console.WriteLine("Please input only ONE integer Number."); 41 } 42 } 43 }