使用事件机制模拟非常6+1

委托和事件,.Net Framework中的应用非常广泛,然而,较好的理解委托和事件对很多接触C#时间不长的人来说并不容易。它们就像一道门槛儿,跨过去的,觉得太容易了,而没有过去的人每次见到委托事件就觉得心慌慌,浑身不自在。
 
我个人还是比较喜欢用面向对象的编程思想去理解逻辑程序,理解编程。下面就用使用事件机制模拟非常6+1的答题过程:
 
分析:从需求中抽象出Host(主持人)类和Guests(嘉宾类);
作为问题的提问者,Host不知道问题如何回答。因此它只能发布这个事件,将事件委托给多个嘉宾去处理。
因此在Host类定义事件,在Guests类中定义事件的响应方法,通过多播委托的“+=”将相应方法添加到事件列表中,最终Host类将触发这个事件,代码如下:
 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 }
原文地址:https://www.cnblogs.com/xyyt/p/3978735.html