.NET中许多类都提供了两种不同的途径可以处理来自系统的事件,一方面我们可以使用事件处理器,另一方面我们可以重写基类的虚方法。这两种方式有各自不同的用途,在派生类中,我们应该使用重写虚方法的方式,来处理系统事件。
关于上述两种方式,我们看以下的代码。
代码
<!--
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> 1 public class MyForm. Form
2 {
3
4 // Other code elided.
5
6 protected override void OnMouseDown(
7 MouseEventArgs e )
8 {
9 try {
10 HandleMouseDown( e );
11 } catch ( Exception e1 )
12 {
13 // add specific error handling here.
14 }
15 // *almost always* call base class to let
16 // other event handlers process message.
17 // Users of your class expect it.
18 base.OnMouseDown( e );
19 }
20 }
21
22
23 public class MyForm. Form
24 {
25
26 // Other code elided.
27
28 public MyForm( )
29 {
30 this.MouseDown += new
31 MouseEventHandler( this.MouseDownHandler );
32 }
33
34 private void MouseDownHandler( object sender,
35 MouseEventArgs e )
36 {
37 try {
38 HandleMouseDown( e );
39 } catch ( Exception e1 )
40 {
41 // add specific error handling here.
42 }
43 }
44 }
我们之所以推荐使用重写父类虚方法的方式来处理事件,是因为以下的原因:
因此,我们在处理派生类中的事件时,推荐使用重写虚方法的方式来处理系统事件,这种情况包括:1)应用程序最外层控件的事件,例如窗体;2)用户自定义控件,例如我们定制一个Button时,需要重画Button的外观以及定制Button的Click事件,这时就应该采用重写虚方法的方式进行。
在以下情况下,我们应该使用事件处理器的方式来处理系统事件:
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/12639172/viewspace-625929/ ,如需转载,请注明出处,否则将追究法律责任。