『Spring.NET』IoC 中的事件处理
C#中的事件是什么样的?
In C# events are built right into the language thanks to the event keyword. Under the scenes, events are essentially a shorthand notation for delegates with some additional guidelines as to what the parameters to an event handler method should be (i.e. a sender System.Object and an System.EventArgs object).
In use, .NET events are combined with one or more event handler methods. Each handler method is programmatically added, or removed, from the event and corresponds to an object's method that should be invoked when a particular event occurs. When more than one handler method is added to an event, then each of the registered methods will be invoked in turn when an event occurs.
说明:
C#中,事件在本质上使用了「代理」(或者叫委托)
C#中,事件的参数是一个Ojbect型的发送者和一个EventArgs类型的事件信息列表
使用中,事件混合了一个或多个事件处理方法
当一个事件发生时,之前加入到这个事件代理的方法会被顺序执行
例如:
1 public class EventSource
2 {
3 public event EventHandler Click;
4
5 public void OnClick()
6 {
7 if (Click != null)
8 {
9 Click(this, EventArgs.Empty); // Fire the event off to the registered handler methods
10 }
11 }
12 }
13 public class EventSourceHandler
14 {
15 public event EventHandler HandlerEvent;
16 }
17
18 public class Test_
19 {
20 void test()
21 {
22 EventSource source = new EventSource();
23 EventSourceHandler eventListener1 = new EventSourceHandler(); // Adding the first event handler method to the event
24 EventSourceHandler eventListener2 = new EventSourceHandler(); // Adding a second event handler method to the event
25
26 source.Click += eventListener1.HandlerEvent;
27 source.Click += eventListener2.HandlerEvent;
28
29 source.OnClick(); // First eventListener1.HandleEvent is invoked, then eventListener2.HandleEvent
30 }
31 }
IoC 中,声明事件处理 EventHandler
…………………………………………………………
配置文件:
1 <object id="eventListener1" type="SpringdotNETEventsExample.TestEventHandler, SpringdotNETEventsExample">
2 <!-- wired up to an event exposed on an instance -->
3 <listener event="Click" method="HandleEvent">
4 <ref object="source"/>
5 </listener>
6 </object>
7
8 <object id="eventListener2" type="SpringdotNETEventsExample.TestEventHandler, SpringdotNETEventsExample">
9 <!-- wired up to an event exposed on an instance -->
10 <listener event="Click" method="HandleEvent">
11 <ref object="source"/>
12 </listener>
13 </object>
说明:
可以在配置项中使用<listener>标签来标注事件处理程序
event 是事件名称,是一个EventHandler名称 注:EventHandler是一个「代理」类型
第二种配置方式:
1 <object id="eventListener" type="SpringdotNETEventsExample.TestEventHandler, SpringdotNETEventsExample">
2 <listener method="Handle.+">
3 <ref object="source"/>
4 </listener>
5 </object>
说明:
你可以使用正则表达式来标注method
Handle.+ 就是一个正则表达式
第三种配置方式:
1 <object id="eventListener" type="SpringdotNETEventsExample.TestEventHandler, SpringdotNETEventsExample">
2 <listener method="HandleEvent" event="Cl.+">
3 <ref object="source"/>
4 </listener>
5 </object>
说明:
你可以在event中使用正则表达式来过滤处理程序
如上代码所示