Delegate 委託,用於傳遞方法的引用(A delegate type represents references to methods with a particular parameter list and return type)。this
用經常使用的觀察者模式來講明一下事件委託過程。blog
第一步:建立一個委託TestDelegate,包含兩個參數,無返回值。事件
/// <summary>
/// 定義委託:用於傳遞委託方法地址
/// </summary>
/// <param name="sender"></param>
/// <param name="e">委託數據爲bool型</param>
public delegate void TestDelegate(object sender, bool e);it
第二步:建立一個發佈者:Test,用於發佈消息。event
/// <summary>
/// 發佈消息類
/// </summary>
public class Test
{
/// <summary>
/// 定義事件委託字段
/// </summary>
public event TestDelegate OnTestHandler;
/// <summary>
/// 發佈消息的方法
/// </summary>
public void DoSomeThing()
{
//發佈消息
OnTestHandler(this, true);
}
}class
第三步:定義方法,用於接受消息,並提供方法引用。object
/// <summary>
/// 定義方法:觀察者(訂閱者)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void OnTestChanged(object sender, bool e)
{
Console.WriteLine(sender.ToString()+Environment.NewLine+ e.ToString());
Console.Read();
}引用
第四步:訂閱事件方法
Test t = new Test();
t.OnTestHandler += new TestDelegate(OnTestChanged);//訂閱消息im
第五步:發佈消息
t.DoSomeThing();
運行: