委托不是方法,它是一種特殊的類型,用於對與該委托有相同簽名(簽名這裡指方法的參數列表)的方法的調用。
委托的一個重要特點是:委托在調用方法時,不必關心方法所屬的對象的類型,它只要求所提供的方法的簽名和委托的簽名相匹配。
委托聲明格式:修飾符 delegate 返回類型 委托名(參數列表)
public delegate void BTEvent();
附一個例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 委托
{
public class ZhangXiaoSan
{
//其實買票的是小張
public static void BuyTicket()
{
Console.WriteLine("買車票!");
}
public static void BuyMovieTicket()
{
Console.WriteLine("買電影票!");
}
public static void BuyStocksTicket()
{
Console.WriteLine("買股票!");
}
}
class Program
{
//聲明一個委托
//委托聲明格式:修飾符 delegate 返回類型 委托名(參數列表)
public delegate void BTEvent();
static void Main(string[] args)
{
Console.WriteLine("===========單個委托============");
BTEvent myDelegate = new BTEvent(ZhangXiaoSan.BuyTicket);
myDelegate();//調用委托
Console.WriteLine("===========委托合並============");
//委托時可以合並的,委托的合並稱為多播
myDelegate += ZhangXiaoSan.BuyMovieTicket;
myDelegate += ZhangXiaoSan.BuyStocksTicket;
myDelegate();//調用委托
Console.WriteLine("==========取消委托=============");
myDelegate -= ZhangXiaoSan.BuyMovieTicket;
myDelegate();//調用委托
Console.ReadKey();
}
}
}