代表(delegate):
它是C#語言裡面的函數指標,代表可以指向某一個函數,在啟動並執行時候調用這個函數的實現。下面來看看它的實現步驟:
- 聲明一個delegate對象。
- 實現和delegate具有相同參數和傳回值的函數實現(可以是靜態和非靜態)。
- 產生一個delegate對象的時候,把你剛剛實現的函數作為參數傳給他的建構函式。
請看下面例子:
using System;
using System.Collections.Generic;
using System.Text;
namespace UsingDelegate
{
public delegate void MyDelegate(string mydelegate);//聲明一個delegate對象
public class TestClass
{
//實現有相同參數和傳回值的函數
public void HelloDelegate(string mydelegate)
{
Console.WriteLine(mydelegate);
}
//實現有相同參數和傳回值的靜態函數
public static void HelloStaticDelegate(string mystaticdelegate)
{
Console.WriteLine(mystaticdelegate);
}
}
class Program
{
static void Main(string[] args)
{
TestClass testClass = new TestClass();
MyDelegate mydelegate = new MyDelegate(testClass.HelloDelegate);//產生delegate對象
mydelegate("Hello delegate");//調用
MyDelegate myStaticDelegate = new MyDelegate(TestClass.HelloStaticDelegate);//產生delegate對象
myStaticDelegate("Hello static delegate");//調用
}
}
}
事件(event):
讓我通過一個例子來類比事件的整個過程:
- 建立一個button類,它裡面有一個click 事件。
- 建立一個Form類,他裡面有一個我們上面定義的button類。
- 要求:當我們使用者單擊button類的時候From類要對他進行處理,輸出一條資訊“我知道你被單擊了”
請看:
首先我們會單擊button,然後button會通知Form,然後From就作出相應。這個過程在C#裡面應該怎麼做到呢?
下面我會列出上述例子的原始碼(這裡就不介紹怎麼聲明event等等內容了):
using System;
using System.Collections.Generic;
using System.Text;
namespace UsingEvent
{
public delegate void ClickEventHandler(object sender, EventArgs e);//聲明一個代表:請看文章最後面Note
public class MyButton //建立MyBottom
{
public event ClickEventHandler ClickEvent;//聲明一個事件
public void Click() //單擊MyButton
{
if (ClickEvent != null)
{
Console.WriteLine("MyButton: 我被單擊了");
ClickEvent(this, null); //拋出事件,給所有相應者
}
}
}
public class MyForm
{
public MyButton myButton = new MyButton();
public MyForm()
{
//添加事件到myButton中,當myButton被單擊的時候就會調用相應的處理函數
myButton.ClickEvent += new ClickEventHandler(OnClickEvent);
}
//事件處理函數
void OnClickEvent(object sender, EventArgs e)
{
Console.WriteLine("MyForm: 我知道你被單擊了!");
}
}
class Program
{
static void Main(string[] args)
{
MyForm form = new MyForm();//產生一個MyForm
form.myButton.Click();//單擊MyForm中的滑鼠,效果就出來了
}
}
}
Note:public delegate void ClickEventHandler(object sender, EventArgs e);這是事件委託標準的聲明方法,其實在參數裡面我們可以不傳,也可以是其他類型的。但是最好還是使用上面的聲明方法,你可以繼承EventArgs,來封裝你要傳送的其他任何參數。