读张子阳老师的委托和事件 2
阅读张子阳老师 园子 事件
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace 张子阳事件 7 { 8 //定义委托 9 public delegate void GreetingDelegate(string name); 10 11 public class GreetingManager 12 { 13 //public void GreetPeople(string name,GreetingDelegate MakeGreeting) 14 //{ 15 // MakeGreeting(name); 16 //} 17 18 19 20 //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 21 22 public GreetingDelegate MakeGreeting1; 23 //与字段对比缺少封装过程 ,怎么像字段那样能封装委托变量! 24 25 //......................................怎么封装呢 ??? 26 27 //然后传个下面的方法 ,实现面向对象的设计思路 28 public void GreetPeople(string name) 29 { 30 if (MakeGreeting1 != null)//如果有方法注册委托变量 31 { 32 MakeGreeting1(name); //通过委托调用方法 33 } 34 } 35 36 37 38 //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 39 private string makeString;//这相当委托 40 41 public string MakeString //这相当事件,它封装了委托类型的变量 42 { 43 get { return makeString; } 44 set { makeString = value; } 45 } 46 public void GreetString() 47 { 48 if (makeString != null) 49 { 50 Console.WriteLine(makeString); 51 } 52 } 53 //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 54 55 56 //这一次我们在这里声明一个事件 和 声明委托变量对比 57 // public GreetingDelegate MakeGreet; 58 public event GreetingDelegate MakeGreet;//对事件的声明 实际是 声明一个私有的委托变量 59 public void GreetPeople1(string name) 60 { 61 MakeGreet(name); 62 } 63 64 } 65 }
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace 张子阳事件 7 { 8 9 class Program 10 { 11 12 static void Main(string[] args) 13 { 14 GreetingManager gm = new GreetingManager(); 15 // gm.MakeGreeting1 = EnglishGreeting; // public 下能赋值! 16 gm.MakeGreeting1 += ChineseGreeting;//把方法加到委托里 17 gm.GreetPeople("Jimmy Zhang"); //注意,这次不需要再传递 delegate1变量 18 //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 19 gm.MakeString = "String__!"; 20 gm.GreetString(); 21 //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 22 23 //gm.MakeGreet = EnglishGreeting;//事件“张子阳事件.GreetingManager.MakeGreet”只能出现在 += 或 -= 的左边(从类型“张子阳事件.GreetingManager”中使用时除外) // = 不能进行赋值! 24 gm.MakeGreet += EnglishGreeting; 25 gm.MakeGreeting1("张子阳"); 26 27 28 29 Console.ReadKey(); 30 } 31 32 33 34 private static void EnglishGreeting(string name) 35 { 36 Console.WriteLine("Morning, " + name); 37 } 38 39 private static void ChineseGreeting(string name) 40 { 41 Console.WriteLine("早上好, " + name); 42 } 43 } 44 }
加上了一些个人整理