本篇文章讲解关于路由事件的相关原理。
什么叫路由事件,字面理解就是事件是可以传递,路由的意思也好理解。路由事件其实就是,事件是会随着某种变化,来回传递。路由事件其实在.NET2.0时期就已经存在了,只不过在一般开发过程中用不到。
从C#3.0开始,就已经封装了关于路由事件的机制。其实这种实现应该可以换个名字来解释。我们可以给路由事件起个便于理解的名字,“事件的路由设计模式”。我们都知道,任何大的框架都是从微小的基本语法开始编写的,平台、语言给我们提供的仅仅是一些能满足日常需求的东西;好东西还得我们自己去写、去创新。在常见的设计模式中,少不了对事件的使用,本人深有体会。是不是高手,不能用他会哪种框架、会哪种语言,而是要看他对他使用的语言所理解程度,能否将一门语言玩的炉火纯青,能否写出高效、简单的框架;这才是高手。这也是很多初学者所喜欢犯的毛病。
路由事件在一些复杂的系统设计中至关重要,比如我有一个对象,这个对象是一个属于容器类的对象,就好比我们Windows应用程序中的Form窗体,这个窗体用来承载一些其他的子窗体。然而这样的递归性的设计,经常性的出现。我们在搭建一个界面时,往这个界面上堆积了很多小的窗口。这些小的窗口又堆积了一些更小的窗口。在设计具有层次性的架构时,我们需要考虑这些对象不能被埋的太深,但是又要保持对象的结构原理,就像下图中所示;
1:
其实实现原理就是将事件向下传递,父控件要循环的判断每一个子控件是否被订阅了相关事件,如果父控件捕获到的这个事件子控件也需要,那么就可以将事件向下路由了;
2:
如果我们需要框架支持路由事件的化,那么我们在前期设计的时候,需要将对象进行提取,对需要路由事件的对象进行基类封装;就好比我们从Control控件的基类开始。
下面我们来看一个小例子,以帮助大家能理解原理,在自己开发项目的时候能用的上。
一:容器对象代码:
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace 路由事件
- {
- ///<summary>
- ///容器类
- ///</summary>
- public class Container
- {
- ///<summary>
- ///鼠标单击事件
- ///</summary>
- public event EventHandlerClick;
- ///<summary>
- ///子对象集合
- ///</summary>
- private List<Child>childlist= new List<Child>();
- ///<summary>
- ///触发当前对象的Click事件
- ///</summary>
- public void OnClick()
- {
- Click( "父对象接受到Click事件" , null ); //触发当前父容器的事件
- foreach (Childc in childlist)
- {
- c.OnClick();
- }
- }
- ///<summary>
- ///添加子对象方法
- ///</summary>
- ///<paramname="c"></param>
- public void Add(Childc)
- {
- childlist.Add(c);
- }
- }
- }
二:子对象代码:
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace 路由事件
- {
- ///<summary>
- ///子对象
- ///</summary>
- public class Child
- {
- ///<summary>
- ///鼠标单击事件
- ///</summary>
- public event EventHandlerClick;
- public void OnClick()
- {
- Click( "子对象接受到Click事件" , null );
- }
- }
- }
三:调用代码:
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace 路由事件
- {
- class Program
- {
- static void Main( string []args)
- {
- Containercontainerobject= new Container();
- containerobject.Click+= new EventHandler(containerobject_Click);
- Childchildobject= new Child();
- childobject.Click+= new EventHandler(childobject_Click);
- containerobject.Add(childobject);
- if (Console.ReadLine()== "StartClick" )
- {
- containerobject.OnClick();
- }
- }
- static void childobject_Click( object sender,EventArgse)
- {
- Console.WriteLine((sender as string ));
- Console.ReadLine();
- }
- static void containerobject_Click( object sender,EventArgse)
- {
- Console.WriteLine((sender as string ));
- Console.ReadLine();
- }
- }
- }