转:终于会用c#中的delegate(委托)和event(事件)了
生活随笔
收集整理的這篇文章主要介紹了
转:终于会用c#中的delegate(委托)和event(事件)了
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
第一個例子:
public class DelegateTest {// 聲明delegate對象 public delegate void CompareDelegate(int a,int b);// 欲傳遞的方法,它與CompareDelegate具有相同的參數和返回值類型 public static void Compare(int a,int b){Console.WriteLine((a>b).ToString());}public static void Main(){// 創建delegate對象 CompareDelegate cd = new CompareDelegate(DelegateTest.Compare);// 調用delegate cd(1,2);} }再來一個例子:
public delegate void MyTestDelegate(int i); public class Program {public static void Main(){//創建delegateReceiveDelegateArgsFunc(new MyTestDelegate(DelegateFunction));}//這個方法接收一個delegate類型的參數,也就是接收一個函數作為參數public static void ReceiveDelegateArgsFunc(MyTestDelegate func){func(21);}//欲傳遞的方法public static void DelegateFunction(int i){System.Console.WriteLine("傳過來的參數為: {0}.", i);} }?
?
三、事件,讓你明白傻瓜式的OnClick是怎么來的
?
C#中的事件處理實際上是一種具有特殊簽名的delegate,象下面這個樣子:
public delegate void MyEventHandler(object sender, MyEventArgs e);?
其中的兩個參數,sender代表事件發送者,e是事件參數類。MyEventArgs類用來包含與事件相關的數據,所有的事件參數類都必須從 System.EventArgs類派生。當然,如果你的事件不含參數,那么可以直接用System.EventArgs類作為參數。
好了,咱們就以OnClick為例說說事件的實現吧。
?
//這里自定義一個EventArgs,因為我想知道Clicker public class ButtonClickArgs : EventArgs {public string Clicker; }public class MyButton {//定義一個delegate委托public delegate void ClickHandler(object sender, ButtonClickArgs e);//定義事件,類型為上面定義的ClickHandler委托public event ClickHandler OnClick;public void Click(){//...觸發之前可能做了n多操作//.....//這時觸發Click事件,并傳入參數Clicker為本博主ivyOnClick(this, new ButtonClickArgs() { Clicker = "ivy" });} }public class Program {public static void Main(){MyButton btn = new MyButton();//注冊事件,把btn_OnClick方法壓入事件隊列,//可以+=多個,這里簡單點就壓入一個吧。btn.OnClick += new MyButton.ClickHandler(btn_OnClick);}this.button1.Click += new System.EventHandler(this.button1_Click);//原本雙擊的效果是這樣//怎么看到這個函數很熟悉吧,就是你原來雙擊button自動產生的代碼public static void btn_OnClick(object sender, ButtonClickArgs e){Console.WriteLine("真賤,我居然被ivy點擊了!");} }?
?
轉載于:https://www.cnblogs.com/bantongshui/p/3189711.html
總結
以上是生活随笔為你收集整理的转:终于会用c#中的delegate(委托)和event(事件)了的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: groovy 字符串截取最后一个_pyt
- 下一篇: 具体的压栈指令,例子