posts - 17,  comments - 2,  trackbacks - 0

在 .Net 中实现自定义事件

 

  .Net 中的自定义事件,其实是利用委托实现,大概可以分为以下几个步骤:
1、定义事件传送的 EventArgs ,当然也可以直接使用系统的 EventArgs。
2、定义该事件类型的委托。
3、定义事件的处理方法。
4、在需要的地方抛出事件,抛出的事件会在外部被捕捉到。
我们以一个简单的计算程序为例讲解,该程序实现计算两个给定数字的和,当结果<=100时,正常计算,但结果>100时,触发事件。然后我们在计算方法外捕捉该事件。这就是整个自定义事件及捕捉的过程。
代码如下,说明请查看注释:

  1. // Step-1: 首先定义一个新的 EventArgs ,其中包括一个属性,用于传送超过100的结果值
  2. // 要注意的是:该类要继承自系统的 EventArgs 类。需要多个属性时定义方法与 HighValue 类似。
  3. class LevelHighArgs : EventArgs
  4. {
  5.         int _highValue = 0;
  6.         public int HighValue
  7.         {
  8.             get { return _highValue; }
  9.             set { _highValue = value; }
  10.         }
  11.         public LevelHighArgs(int _highValue)
  12.         {
  13.             this._highValue = _highValue;
  14.         }
  15. }
  16.     
  17.   // Step-2: 处理类。在该类中定义委托,和事件处理方法。
  18.   class AddTowInt
  19.   {
  20.        // 委托定义
  21.         public delegate void LevelHigh(object sender, LevelHighArgs e);
  22.        // 委托类型的事件处理方法
  23.         public event LevelHigh OnLevelHigh;
  24.         int _addedValue = 0;
  25.         public int AddedValue
  26.         {
  27.             get { return _addedValue; }
  28.             set { _addedValue = value; }
  29.         }
  30.         public AddTowInt()
  31.         { }
  32.         public void DoAdd(int a1, int a2)
  33.         {
  34.             _addedValue = a1 + a2;
  35.             if (_addedValue > 100)
  36.             {
  37.                 LevelHighArgs lha = new LevelHighArgs(_addedValue - 100);
  38.                 
  39.                 // 在结果 > 100 时,抛出事件
  40.                 OnLevelHigh(this, lha);
  41.             }
  42.         }
  43.  }
  44.     
  45.     // 使用及事件的捕捉
  46. class Program
  47. {
  48.         static void Main(string[] args)
  49.         {
  50.          // 计算程序对象
  51.             AddTowInt ati = new AddTowInt();
  52.             // 注册事件处理程序
  53.             ati.OnLevelHigh += new AddTowInt.LevelHigh(ati_OnLevelHigh);
  54.             // 传送测试数据。此时结果为 101 会触发事件,可换成 23, 77 调用会看到事件没有触发。
  55.             ati.DoAdd(23, 78);
  56.             Console.WriteLine(ati.AddedValue);
  57.             Console.ReadLine();
  58.         }
  59.         static void ati_OnLevelHigh(object sender, LevelHighArgs e)
  60.         {
  61.          // 此处 e 中可以看到有一个 HighValue 属性,该值就是我们定义在 LevelHighArgs 中的属性
  62.             Console.WriteLine("结果已经超过 100: " + e.HighValue);
  63.         }
  64. }

posted on 2008-11-03 00:58 BeyondCN 阅读(494) 评论(0)  编辑 收藏 引用 所属分类: .NET

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理