所以我這裡就通過C#事件來說Delegate(委托)。先看一段示例代碼:
代碼
public delegate void ProcessEventHandler(string name);
public class CharlesLog
{
public event ProcessEventHandler processEvent;
public void ProcessHandler(string name)
{
if (processEvent != null)
{
processEvent(name);
}
else
{
processEvent = new ProcessEventHandler(DefaultHandler);
processEvent(name);
}
}
public void DefaultHandler(string name)
{
Console.WriteLine("default Process!");
}
}
class Program
{
static void Main(string[] args)
{
CharlesLog charlesLog = new CharlesLog();
charlesLog.processEvent += new ProcessEventHandler(CustomProcess);
charlesLog.ProcessHandler("CharlesChen");
}
public static void CustomProcess(string name)
{
Console.WriteLine("custom Process!");
}
}
根據這個Demo,針對委托和事件而言,需要注意一些要點,我這裡列舉出來:
1、 上面的委托委托實例化用的是.Net 1.1的語法:(注:)隨著Net版本升級,委托實例化的語法簡化,在2.0有匿名方法,以及3.0的Lambda表達式更能符合人類語言。
charlesLog.processEvent += new ProcessEventHandler(CustomProcess);
2、 申明事件的語法是:”修飾符&r