C#委托,事件理解入门 (译稿)

时间:2022-03-20 05:49:38

原文地址:http://www.codeproject.com/Articles/4773/Events-and-Delegates-Simplified

引用翻译地址:http://www.cnblogs.com/finesite/articles/255884.html

目录

  1. 导论
  2. 什么是委托
  3. 事件的理解
  4. 事件关键字
  5. 最后

1. 导论

在学习C#中的委托和事件过程中,我读了许多文章来理解他们二者究竟是怎么一回事,以及如何使用他们,现在我将整个的理解过程陈述以下,我学到的每一方面,恐怕也是你们需要掌握的:-)。

2. 什么是委托?

委托和事件这两个概念是完全配合的。委托仅仅是函数指针,那就是说,它能够引用函数,通过传递地址的机制完成。
委托是一个类,当你对它实例化时,要提供一个引用函数,将其作为它构造函数的参数。
每一个委托都有自己的签名,例如:

1 Delegate int SomeDelegate(string s,bool b);

是一个委托申明,在这里,提及的签名,就是说SomeDelegate这个委托有string和bool类型的形参,返回一个int类型。
上面提及的:当你对委托实例化时,要提供一个引用函数,将其作为它构造函数的参数。这里要注意了:被引用的这个函数必须和委托有相同的签名。
看下面的函数:

1 private int SomeFunction(string str,bool bln){...}

你可以把这个函数传给SomeDelegate的构造函数,因为他们有相似的签名(换句话说,他们都有相同的形参类型和个数,并且返回相同的数据类型)。

1 SomeDelegate sd = new SomeDelegate(SomeFunction);

sd引用了SomeFunction,也就是说,SomeFunction已被sd所登记注册,如果你调用sd,SomeFunction这个函数也会被调用,记住:我所说SomeFunction的含义,后面,我们会用到它。
现在,你应该知道如何使用委托了,让我们继续理解事件之旅……

3. 事件的理解

我们知道,在C#中:

  • 按钮(Button)就是一个类,当我们单击它时,就触发一次click事件。
  • 时钟(Timer)也是一个类,每过一毫秒,就触发一次tick事件。

让我们通过一个例子来学习,假定有这样的情节:

现在有一个Counter的类,它有一个方法CountTo(int countTo,int reachableNum),该方法表示:在指定的时间段内(0到countTo),当到达指定的时间点reachableNum时,就触发一次NumberReached事件。

它还有一个事件:NumberReached,事件是委托类型的变量。意思是:如果给事件命名,用event关键字和要使用的委托类型申明它即可,如下所示:

1 public event NumberReachedEventHandler NumberReached;

在上面的申明中,NumberReachedEventHandle仅是一个委托,更确切的表示应该是:NumberReachedDelegate。但是微软从不这样认为MouseDelegate或者PaintDelegate... 而是称谓:MouseEventHandler或者PaintEventHandler。所以NumberReachedEventHandler比NumberReachedDelegate听起来更方便一些,OK?好了!

让我们继续,现在你知道了,在我们声明事件之前,需要象下面这样的形式来定义委托:

1 public delegate void NumberReachedEventHandler(object sender,NumberReachedEventArgs e);

现在声明的委托NumberReachedEventHandle,它有一个void返回值,和object,NumberReachedEventArgs两个形参。就像我们在第一节中强调的那样,当实例化委托时,作为实参传入的函数也必须拥有和委托同样的签名。
在你的代码中,你是否用过PaintEventArgs或者MouseEventArgs来确定鼠标的移动位置?是否在触发Paint事件的对象中用过Graphics属性?实际上,为用户提供数据的类都是继承于System.EventArgs类,就是我们常说的事件参数类,如果事件不提供参数,就不定义该类。在我们的例子中,我们通过下面的类提供预期的时间点。

 1     public class NumberReachedEventArgs : EventArgs
 2     {
 3         private int _reached;
 4         public NumberReachedEventArgs(int num)
 5         {
 6             this._reached = num;
 7         }
 8         public int ReachedNumber
 9         {
10             get
11             {
12                 return _reached;
13             }
14         }
15     }

好,有了前面的介绍,让我们到Counter类里面看看:

 1 namespace Events
 2 {
 3     public delegate void NumberReachedEventHandler(object sender, NumberReachedEventArgs e);
 4     /// <summary>
 5     /// Summary description for Counter.
 6     /// </summary>
 7     public class Counter
 8     {
 9         public event NumberReachedEventHandler NumberReached;
10         public Counter()
11         {
12             //
13             // TODO: Add constructor logic here
14             //
15         }
16         public void CountTo(int countTo, int reachableNum)
17         {
18             if (countTo < reachableNum)
19                 throw new ArgumentException("reachableNum should be less than countTo");
20             for (int ctr = 0; ctr <= countTo; ctr++)
21             {
22                 if (ctr == reachableNum)
23                 {
24                     NumberReachedEventArgs e = new NumberReachedEventArgs(reachableNum);
25                     OnNumberReached(e);
26                     return;//don't count any more
27                 }
28             }
29         }
30         protected virtual void OnNumberReached(NumberReachedEventArgs e)
31         {
32             if (NumberReached != null)
33             {
34                 NumberReached(this, e);//Raise the event
35             }
36         }
37     }
38 }

在Counter中,如果到达指定的时间点,就触发一次事件,有以下几个方面需要注意:

  • 通过调用NumberReached(它是NumberReachedEventHandler委托的实例)来完成一次触发事件。
  • NumberReached(this,e);通过这种方式,可以调用所有的注册函数。
  • 通过NumberReachedEventArgs e=new NumberReachedEventArgs(reachableNum);为所有的注册函数提供事件数据。

看了上面的代码,你可能要问了:为什么我们直接用OnNumberReached(NumberReachedEventArgs e)方法来调用NumberReached(this,e),而不用下面的代码呢?

 1 if(ctr == reachableNum)
 2 {
 3     NumberReachedEventArgs e = new NumberReachedEventArgs(reachableNum);
 4     //OnNumberReached(e);
 5     if(NumberReached != null)
 6     {
 7         NumberReached(this, e);//Raise the event
 8     }
 9     return;//don't count any more
10 }

这个问题问得很好,那就让我们再看一下OnNumberReached 签名:
protected virtual void OnNumberReached(NumberReachedEventArgs e)
①你也明白 关键字protected限定了 只有从该类继承的类才能调用该类中的所有方法。
②关键字 virtual 表明了 在继承类中可以重写该方法。
这两点非常有用,假设你在写一个从Counter继承而来的类,通过重写OnNumberReached 方法,你可以在事件触发之前,进行一次其他的工作。

1 protected override void OnNumberReached(NumberReachedEventArgs e)
2 {
3     //Do additional work
4     base.OnNumberReached(e);
5 }

注意:如果你没有调用base.OnNumberReached(e), 那么从不会触发这个事件!在你继承该类而想剔出它的一些其他事件时,使用该方式是非常有用的。
还要注意到:委托 NumberReachedEventHandler 是在类定义的外部,命名空间内定义的,对所有类来说是可见的。
好,该我们来实际操作使用Counter类了。
在我们简单的应用程序中,我们有两个文本框,分别是:txtCountTo和txtReachable:

C#委托,事件理解入门 (译稿)

下面是btnRun的click事件:

 1        private void btnRun_Click(object sender, System.EventArgs e)
 2        {
 3            if(txtCountTo.Text == "" || txtReachable.Text=="")
 4            return;
 5            oCounter.CountTo(Convert.ToInt32(txtCountTo.Text), Convert.ToInt32(txtReachable.Text));
 6        }
 7 
 8        private void oCounter_NumberReached(object sender, NumberReachedEventArgs e)
 9        {
10            MessageBox.Show("Reached: " + e.ReachedNumber.ToString());
11        }

初始化事件处理的语法如下:

1 oCounter = new Counter();
2 oCounter.NumberReached += new NumberReachedEventHandler(oCounter_NumberReached);

现在你明白了你刚才所做的一切,仅仅初始化 NumberReachedEventHandler 委托类型的对象(就像你实例化其他对象一样),注意到 oCounter_NumberReached 方法的签名与我前面提到的相似。
还要注意我们用的是+= 而不是=;这是因为委托是特殊的对象,它可以引用多个对象(在这里是指它可以引用多个函数)。For example 如果有另外一个和oCounter_NumberReached一样具有相同签名的函数oCounter_NumberReached2,这两个函数都可以被引用:
oCounter = new Counter();
oCounter.NumberReached += new NumberReachedEventHandler(oCounter_NumberReached);
oCounter.NumberReached += new NumberReachedEventHandler(oCounter_NumberReached2);
现在,触发一个事件后,上面两个函数被依次调用。
视情况而定,如果你想让oCounter_NumberReached2在NumberReached事件发生后不再被调用,可以简单地这样写:
oCounter.NumberReached -= new NumberReachedEventHandler(oCounter_NumberReached2);

5. 最后

让我们看一下完整的源代码,以供参考:

 1 using System;
 2 
 3 namespace Events
 4 {
 5     public delegate void NumberReachedEventHandler(object sender, NumberReachedEventArgs e);
 6 
 7     /// <summary>
 8     /// Summary description for Counter.
 9     /// </summary>
10     public class Counter
11     {
12         public event NumberReachedEventHandler NumberReached;
13         
14         public Counter()
15         {
16             //
17             // TODO: Add constructor logic here
18             //
19         }
20         public void CountTo(int countTo, int reachableNum)
21         {
22             if(countTo < reachableNum)
23                 throw new ArgumentException("reachableNum should be less than countTo");
24             for(int ctr=0;ctr<=countTo;ctr++)
25             {
26                 if(ctr == reachableNum)
27                 {
28                     NumberReachedEventArgs e = new NumberReachedEventArgs(reachableNum);
29                     OnNumberReached(e);
30                     return;//don't count any more
31                 }
32             }
33         }
34 
35         protected virtual void OnNumberReached(NumberReachedEventArgs e)
36         {
37             if(NumberReached!=null)
38             {
39                 NumberReached(this, e);
40             }
41         }
42     }
43 
44     public class NumberReachedEventArgs : EventArgs
45     {
46         private int _reached;
47         public NumberReachedEventArgs(int num)
48         {
49             this._reached = num;
50         }
51         public int ReachedNumber
52         {
53             get
54             {
55                 return _reached;
56             }
57         }
58     }
59 }

 

  1 using System;
  2 using System.Drawing;
  3 using System.Collections;
  4 using System.ComponentModel;
  5 using System.Windows.Forms;
  6 using System.Data;
  7 
  8 namespace Events
  9 {
 10     /// <summary>
 11     /// Summary description for Form1.
 12     /// </summary>
 13     public class Form1 : System.Windows.Forms.Form
 14     {
 15         Counter oCounter = null;
 16 
 17         private System.Windows.Forms.Button cmdRun;
 18         private System.Windows.Forms.TextBox txtReachable;
 19         private System.Windows.Forms.TextBox txtCountTo;
 20         private System.Windows.Forms.Label label1;
 21         private System.Windows.Forms.Label label2;
 22         private System.Windows.Forms.Button btnRemoveDelegate;
 23         /// <summary>
 24         /// Required designer variable.
 25         /// </summary>
 26         private System.ComponentModel.Container components = null;
 27 
 28         public Form1()
 29         {
 30             //
 31             // Required for Windows Form Designer support
 32             //
 33             InitializeComponent();
 34 
 35             //
 36             // TODO: Add any constructor code after InitializeComponent call
 37             //
 38             oCounter = new Counter();
 39             oCounter.NumberReached += new NumberReachedEventHandler(oCounter_NumberReached);
 40             oCounter.NumberReached += new NumberReachedEventHandler(oCounter_NumberReached2);
 41         }
 42 
 43         /// <summary>
 44         /// Clean up any resources being used.
 45         /// </summary>
 46         protected override void Dispose( bool disposing )
 47         {
 48             if( disposing )
 49             {
 50                 if (components != null) 
 51                 {
 52                     components.Dispose();
 53                 }
 54             }
 55             base.Dispose( disposing );
 56         }
 57 
 58         #region Windows Form Designer generated code
 59         /// <summary>
 60         /// Required method for Designer support - do not modify
 61         /// the contents of this method with the code editor.
 62         /// </summary>
 63         private void InitializeComponent()
 64         {
 65             this.cmdRun = new System.Windows.Forms.Button();
 66             this.txtReachable = new System.Windows.Forms.TextBox();
 67             this.txtCountTo = new System.Windows.Forms.TextBox();
 68             this.label1 = new System.Windows.Forms.Label();
 69             this.label2 = new System.Windows.Forms.Label();
 70             this.btnRemoveDelegate = new System.Windows.Forms.Button();
 71             this.SuspendLayout();
 72             // 
 73             // cmdRun
 74             // 
 75             this.cmdRun.Location = new System.Drawing.Point(16, 72);
 76             this.cmdRun.Name = "cmdRun";
 77             this.cmdRun.Size = new System.Drawing.Size(48, 23);
 78             this.cmdRun.TabIndex = 2;
 79             this.cmdRun.Text = "Run";
 80             this.cmdRun.Click += new System.EventHandler(this.cmdRun_Click);
 81             // 
 82             // txtReachable
 83             // 
 84             this.txtReachable.Location = new System.Drawing.Point(144, 40);
 85             this.txtReachable.Name = "txtReachable";
 86             this.txtReachable.Size = new System.Drawing.Size(56, 20);
 87             this.txtReachable.TabIndex = 1;
 88             this.txtReachable.Text = "";
 89             // 
 90             // txtCountTo
 91             // 
 92             this.txtCountTo.Location = new System.Drawing.Point(144, 16);
 93             this.txtCountTo.Name = "txtCountTo";
 94             this.txtCountTo.Size = new System.Drawing.Size(56, 20);
 95             this.txtCountTo.TabIndex = 0;
 96             this.txtCountTo.Text = "";
 97             // 
 98             // label1
 99             // 
100             this.label1.AutoSize = true;
101             this.label1.Location = new System.Drawing.Point(16, 16);
102             this.label1.Name = "label1";
103             this.label1.Size = new System.Drawing.Size(51, 13);
104             this.label1.TabIndex = 3;
105             this.label1.Text = "Count To";
106             // 
107             // label2
108             // 
109             this.label2.AutoSize = true;
110             this.label2.Location = new System.Drawing.Point(16, 40);
111             this.label2.Name = "label2";
112             this.label2.Size = new System.Drawing.Size(99, 13);
113             this.label2.TabIndex = 4;
114             this.label2.Text = "Reach this number";
115             // 
116             // btnRemoveDelegate
117             // 
118             this.btnRemoveDelegate.Location = new System.Drawing.Point(16, 104);
119             this.btnRemoveDelegate.Name = "btnRemoveDelegate";
120             this.btnRemoveDelegate.Size = new System.Drawing.Size(168, 23);
121             this.btnRemoveDelegate.TabIndex = 5;
122             this.btnRemoveDelegate.Text = "Remove second handler";
123             this.btnRemoveDelegate.Click += new System.EventHandler(this.btnRemoveDelegate_Click);
124             // 
125             // Form1
126             // 
127             this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
128             this.ClientSize = new System.Drawing.Size(224, 134);
129             this.Controls.AddRange(new System.Windows.Forms.Control[] {
130                                                                           this.btnRemoveDelegate,
131                                                                           this.label2,
132                                                                           this.label1,
133                                                                           this.txtCountTo,
134                                                                           this.txtReachable,
135                                                                           this.cmdRun});
136             this.Name = "Form1";
137             this.Text = "Events";
138             this.ResumeLayout(false);
139 
140         }
141         #endregion
142 
143         /// <summary>
144         /// The main entry point for the application.
145         /// </summary>
146         [STAThread]
147         static void Main() 
148         {
149             Application.Run(new Form1());
150         }
151 
152         private void cmdRun_Click(object sender, System.EventArgs e)
153         {
154             if(txtCountTo.Text == "" || txtReachable.Text=="")
155                 return;
156             oCounter.CountTo(Convert.ToInt32(txtCountTo.Text), Convert.ToInt32(txtReachable.Text));
157         }
158 
159         private void oCounter_NumberReached(object sender, NumberReachedEventArgs e)
160         {
161             MessageBox.Show("Reached: " + e.ReachedNumber.ToString());
162         }
163         private void oCounter_NumberReached2(object sender, NumberReachedEventArgs e)
164         {
165             MessageBox.Show("Reached2: " + e.ReachedNumber.ToString());
166         }
167 
168         private void btnRemoveDelegate_Click(object sender, System.EventArgs e)
169         {
170             oCounter.NumberReached -= new NumberReachedEventHandler(oCounter_NumberReached2);
171             oCounter.CountTo(Convert.ToInt32(txtCountTo.Text), Convert.ToInt32(txtReachable.Text));
172         }
173     }
174 }