委托是對類別中方法的參考,本身不包含實作,只指向符合簽章的方法。類似 C++ 的函數指標或 Delphi 的程序型別,但具型別安全。
委托實現「方法作為參數」傳遞,支援回呼、事件處理、策略模式等。呼叫者不需知悉具體執行方法,僅透過委托調用。
class Secretary
{
private delegate string Do(string command);
public Do DoIt;
public void ExecuteCommand(string command)
{
switch (command)
{
case "Market":
DoIt = new Do(new MarketMan().GetMarketInfo);
break;
case "Product":
DoIt = new Do(ProductMan.ProduceProduct);
break;
}
DoIt(command);
}
}
class MarketMan { public string GetMarketInfo(string cmd) { /*...*/ return "Market Info"; } }
class ProductMan { public static string ProduceProduct(string cmd) { /*...*/ return "Product Info"; } }
class Boss
{
public static void Main()
{
new Secretary().ExecuteCommand("Market");
}
}