标签:style blog color io os 使用 ar div sp
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 namespace 使用事件模拟非常6_1 6 { 7 class Program 8 { 9 static void Main(string[] args) 10 { 11 Host host = new Host(); 12 host.Name = "李咏"; 13 host.eventArgs.QuestionArgs = "C#的事件如何实现的"; 14 Guest[] gArray = new Guest[2]{ 15 new GuestA(){Gname="张三"}, 16 new GuestB(){Gname="李四"} 17 }; 18 //将嘉宾的答题方法加入委托链 19 host.questionEvent += gArray[0].answer; 20 host.questionEvent += gArray[1].answer; 21 //触发事件 22 host.Ask(); 23 Console.ReadLine(); 24 } 25 } 26 /// 27 /// 问题参数类 28 /// 29 public class QuestionArg :EventArgs 30 { 31 public string QuestionArgs { get; set; } 32 } 33 /// 34 /// 主持人类 35 /// 36 public class Host 37 { 38 public Host() 39 { 40 eventArgs = new QuestionArg(); 41 } 42 //主持人名称 43 public string Name { get; set; } 44 public QuestionArg eventArgs { get; set; } 45 //定义委托与事件 46 public delegate void QuestionHandler(object sender, QuestionArg args); 47 public event QuestionHandler questionEvent; 48 //主持人提问问题的方法 49 public void Ask() 50 { 51 Console.WriteLine("开始答题"); 52 questionEvent(this, this.eventArgs); 53 } 54 } 55 /// 56 /// 嘉宾父类 57 /// 58 public class Guest 59 { 60 public string Gname { get; set; } 61 //答题方法,虚方法 62 public virtual void answer(object sender, QuestionArg e) 63 { 64 Console.WriteLine("事件的发出者:" + (sender as Host).Name); 65 Console.WriteLine("问题是:"+e.QuestionArgs); 66 } 67 } 68 /// 69 /// 嘉宾A 70 /// 71 public class GuestA:Guest 72 { 73 public override void answer(object sender, QuestionArg e) 74 { 75 base.answer(sender, e); 76 Console.WriteLine(this.Gname + "开始答题:我不知道!"); 77 } 78 } 79 /// 80 /// 嘉宾B 81 /// 82 public class GuestB : Guest 83 { 84 public override void answer(object sender, QuestionArg e) 85 { 86 base.answer(sender, e); 87 Console.WriteLine(this.Gname + "开始答题:这个有点难!"); 88 } 89 } 90 }
标签:style blog color io os 使用 ar div sp
原文地址:http://www.cnblogs.com/xyyt/p/3978735.html