C#事件机制(记住流程)
生活随笔
收集整理的這篇文章主要介紹了
C#事件机制(记住流程)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
轉(zhuǎn)自:http://jimmyloveforever.blog.163.com/blog/static/119775247200951303935836/
1,C#事件機(jī)制是基于委托實(shí)現(xiàn)的,因此要首先定義一個委托EventHandler:? ? ? ? ? ? ? ? ? ? ? ?public?delegate?void?EventHandler(object?from?,?myEventArgs?e)?
System.EventArgs是包含事件數(shù)據(jù)的類的基類,在代碼中可直接使用EventArgs類。 myEventArgs類派生于EventArgs類,實(shí)現(xiàn)自定義事件數(shù)據(jù)的功能。這里from表示發(fā)生事件的對象。?
2,定義事件格式為:
???? ?event?事件的委托名?事件名?
如事件TextOut定義:?
?????public?event?EventHandler?TextOut;?
3,事件的激活一般寫成:?
if?(TextOut?!=?null)?
???????????? ?TextOut(this,new?EventArgs());?
?檢查TextOut事件有沒有被訂閱,如不為null,則表示有用戶訂閱。訂閱事件的是?
TestApp類,首先實(shí)例化EventSource,然后訂閱事件:?
evsrc.TextOut?+=?new??EventSource.EventHandler(CatchEvent);?
也可以取消訂閱:?
evsrc.TextOut?-=?new??EventSource.EventHandler(CatchEvent);?
View Code using System; using System.Collections.Generic; using System.Linq; using System.Text;// 定義事件包含數(shù)據(jù) public class MyEventArgs : EventArgs {private string StrText;public MyEventArgs(string StrText){this.StrText = StrText;}public string GetStrText{get{return StrText;}} } // 發(fā)布事件的類 class EventSource {MyEventArgs EvArgs = new MyEventArgs("觸發(fā)事件");// 定義委托 public delegate void EventHandler(object sender, MyEventArgs e);// 定義事件 public event EventHandler TextOut;// 激活事件的方法 public void TriggerEvent(){if (TextOut == null)TextOut(this, EvArgs);} } // 訂閱事件的類 class TestApp {public static void Main(){EventSource evsrc = new EventSource();// 訂閱事件 evsrc.TextOut += new EventSource.EventHandler(CatchEvent);// 觸發(fā)事件 evsrc.TriggerEvent();Console.WriteLine("------");// 取消訂閱事件 evsrc.TextOut -= new EventSource.EventHandler(CatchEvent);// 觸發(fā)事件 evsrc.TriggerEvent();Console.WriteLine("------"); // 事件訂閱已取消,什么也不執(zhí)行 TestApp theApp = new TestApp();evsrc.TextOut += new EventSource.EventHandler(theApp.InstanceCatch);evsrc.TriggerEvent();Console.WriteLine("------");}// 處理事件的靜態(tài)方法 public static void CatchEvent(object from, MyEventArgs e){Console.WriteLine("CatchEvent:{0}", e.GetStrText);}// 處理事件的方法 public void InstanceCatch(object from, MyEventArgs e){Console.WriteLine("InstanceCatch:{0},e.GetStrText");} }
?
轉(zhuǎn)載于:https://www.cnblogs.com/anbylau2130/archive/2013/02/21/2920687.html
總結(jié)
以上是生活随笔為你收集整理的C#事件机制(记住流程)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HttpClient 通过资源URL下载
- 下一篇: [No0000DB]C# FtpClie