通过Demo来细看C#事件的内在机制
所以我这里就通过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!");
}
}
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
补充:软件开发 , C# ,