1、定義
delegate是C#中的一種類型,它實際上是一個能夠持有對某個方法的引用的類。與其它的類不同,delegate類能夠擁有一個簽名(signature),並且它"只能持有與它的簽名相匹配的方法的引用"。
它允許你傳遞一個類A的方法m給另一個類B的對象,使得類B的對象能夠調用這個方法m。
delegate是面向對象、類型安全、可靠的受控(managed)對象。也就是說,運行時能夠保證delegate指向一個有效的方法,你無須擔心delegate會指向無效地址或者越界地址。
2、委託的聲明原型
delegate <函數返回類型> <委託名> (<函數參數>)
public delegate void CheckDelegate(int number);
委託在.net內相當於聲明瞭一個類,類如果不實例化爲對象,很多功能是沒有辦法使用的,委託也是如此。
3、委託的實例化
委託實例化的原型
<委託類型> <實例化名>=new <委託類型>(<註冊函數>)
CheckDelegate checkDelegate=new CheckDelegate(CheckMod);
4、創建步驟
(1)聲明一個delegate對象,它應當與你想要傳遞的方法具有相同的參數和返回值類型。
(2)創建delegate對象,並"將你想要傳遞的函數作爲參數傳入"。
(3)通過上一步創建的對象來調用方法
創建一個Subject對象
using System;
public class ConcreteSubject
{
/// <summary>
/// 聲明委託
/// </summary>
public delegate void CustomerEventHandler(String state);
// 聲明一個委託事件,類型爲 CustomerEventHandler
public event CustomerEventHandler Update;
static ConcreteSubject instance;
private string subjectState;
/// <summary>
/// 觀察者理應是單利模式
/// </summary>
/// <value>The get.</value>
public static ConcreteSubject Get()
{
if(instance == null)
{
instance = new ConcreteSubject ();
}
return instance;
}
public void Notify(string state)
{
if (Update != null)
{
// 使用事件來通知給訂閱者
Update(state);
}
}
}
創建一個監聽着
using System;
using UnityEngine;
public class ConcreteObserver
{
public void GiveInvoice(string state)
{
Console.WriteLine("我是會計,我來開具發票。");
Debug.Log ("===================GiveInvoice==============:"+state);
}
}
使用的時候
ConcreteObserver observer_1 = new ConcreteObserver ();
ConcreteObserver observer_2 = new ConcreteObserver ();
ConcreteSubject.Get ().Update += observer_1.GiveInvoice;
ConcreteSubject.Get ().Update += observer_2.GiveInvoice;