在 .Net 中实现自定义事件
.Net 中的自定义事件,其实是利用委托实现,大概可以分为以下几个步骤:
1、定义事件传送的 EventArgs ,当然也可以直接使用系统的 EventArgs。
2、定义该事件类型的委托。
3、定义事件的处理方法。
4、在需要的地方抛出事件,抛出的事件会在外部被捕捉到。
我们以一个简单的计算程序为例讲解,该程序实现计算两个给定数字的和,当结果<=100时,正常计算,但结果>100时,触发事件。然后我们在计算方法外捕捉该事件。这就是整个自定义事件及捕捉的过程。
代码如下,说明请查看注释:
- // Step-1: 首先定义一个新的 EventArgs ,其中包括一个属性,用于传送超过100的结果值
- // 要注意的是:该类要继承自系统的 EventArgs 类。需要多个属性时定义方法与 HighValue 类似。
- class LevelHighArgs : EventArgs
- {
- int _highValue = 0;
- public int HighValue
- {
- get { return _highValue; }
- set { _highValue = value; }
- }
- public LevelHighArgs(int _highValue)
- {
- this._highValue = _highValue;
- }
- }
- // Step-2: 处理类。在该类中定义委托,和事件处理方法。
- class AddTowInt
- {
- // 委托定义
- public delegate void LevelHigh(object sender, LevelHighArgs e);
- // 委托类型的事件处理方法
- public event LevelHigh OnLevelHigh;
- int _addedValue = 0;
- public int AddedValue
- {
- get { return _addedValue; }
- set { _addedValue = value; }
- }
- public AddTowInt()
- { }
- public void DoAdd(int a1, int a2)
- {
- _addedValue = a1 + a2;
- if (_addedValue > 100)
- {
- LevelHighArgs lha = new LevelHighArgs(_addedValue - 100);
- // 在结果 > 100 时,抛出事件
- OnLevelHigh(this, lha);
- }
- }
- }
- // 使用及事件的捕捉
- class Program
- {
- static void Main(string[] args)
- {
- // 计算程序对象
- AddTowInt ati = new AddTowInt();
- // 注册事件处理程序
- ati.OnLevelHigh += new AddTowInt.LevelHigh(ati_OnLevelHigh);
- // 传送测试数据。此时结果为 101 会触发事件,可换成 23, 77 调用会看到事件没有触发。
- ati.DoAdd(23, 78);
- Console.WriteLine(ati.AddedValue);
- Console.ReadLine();
- }
- static void ati_OnLevelHigh(object sender, LevelHighArgs e)
- {
- // 此处 e 中可以看到有一个 HighValue 属性,该值就是我们定义在 LevelHighArgs 中的属性
- Console.WriteLine("结果已经超过 100: " + e.HighValue);
- }
- }