利用EventHandler系统委托,触发Event


               最近一直在研究委托与事件,下面是我的个人理解

  • NOTE:参考了张子阳的思想,各位大佬可以看看http://www.cnblogs.com/JimmyZhang/archive/2007/09/23/903360.html
  • 1.事件要有委托,参数,事件
  • 2.委托可以自己定义:public delegate void  Boli(object sender,BoliEventAgrs e);
  • 也可以利用EventHandler进行操作,本次使用的是此方法:
  • 前提要声明参数(BoliEventAgrs),此类继承EventArgs而且是必须的;
    1 class BoliEventAgrs : EventArgs//继承系统事件参数接口
    2     {
    3         public readonly int tem;
    4         public BoliEventAgrs(int tem)
    5         {
    6             this.tem = tem;
    7         }
    8     }

 

  1. public event EventHandler<BoliEventAgrs> BoliWaterEvent;
  2. EventHandler是系统自己的带参委托定义为:   public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);
  3. BoliEventAgrs为委托参数,也是事件需要的参数;
  4. BoliWaterEvent为事件名字;
  5. 3.委托,参数,事件都有啦,下面就是写具体方法了,就是你的事件是什么事件,需要干啥的,
  6. 两步走,订阅也就是注册事件,执行触发事件的方法
//注册
boli.BoliWaterEvent += boli1.Alarm; boli.BoliWaterEvent += boli1.Alarm1;
//执行
boli.Boliwater();

4。效果

5.下面是完整代码

using System; namespace DelegateEventObserver { class Program { static void Main(string[] args) { a boli = new a(); b boli1 = new b(); boli.BoliWaterEvent += boli1.Alarm; boli.BoliWaterEvent += boli1.Alarm1; boli.Boliwater(); Console.ReadKey(); } } class BoliEventAgrs : EventArgs//继承系统事件参数接口
 { public readonly int tem; public BoliEventAgrs(int tem) { this.tem = tem; } } class a { //public delegate void Boli(object sender,BoliEventAgrs e);
        public event EventHandler<BoliEventAgrs> BoliWaterEvent;//BoliEventAgrs 为委托参数
        public void Boliwater() { for (int i=0; i<100;i++) { if (i>90) { BoliEventAgrs e = new BoliEventAgrs(i); if (BoliWaterEvent != null) { BoliWaterEvent(this, e); } } } } } /// <summary>
    /// 委托方法,事件注册方法,参数e为 控制温度 /// </summary>
    class b { public void Alarm(object sender,BoliEventAgrs e) { if (e.tem>95) { Console.WriteLine("水温{0}",e.tem); } } public void Alarm1(object sender, BoliEventAgrs e) { if (e.tem >98) { Console.WriteLine("水温{0},马上开啦", e.tem); } } } }

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM