日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > C# >内容正文

C#

C#事件机制(记住流程)

發(fā)布時間:2023/12/9 C# 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。