C#委托和事件
委托和事件
复制代码public class EventClass{ // Declare the delegate type: public delegate void CustomEventHandler(object sender, System.EventArgs e); // Declare the event variable using the delegate type: public event CustomEventHandler CustomEvent; public void InvokeEvent() { // Invoke the event from within the class that declared the event: CustomEvent(this, System.EventArgs.Empty); }}class TestEvents{ private static void CodeToRun(object sender, System.EventArgs e) { System.Console.WriteLine("CodeToRun is executing"); } private static void MoreCodeToRun(object sender, System.EventArgs e) { System.Console.WriteLine("MoreCodeToRun is executing"); } static void Main() { EventClass ec = new EventClass(); ec.CustomEvent += new EventClass.CustomEventHandler(CodeToRun); ec.CustomEvent += new EventClass.CustomEventHandler(MoreCodeToRun); System.Console.WriteLine("First Invocation:"); ec.InvokeEvent(); ec.CustomEvent -= new EventClass.CustomEventHandler(MoreCodeToRun); System.Console.WriteLine("\nSecond Invocation:"); ec.InvokeEvent(); }}
输出
First Invocation:
CodeToRun is executing
MoreCodeToRun is executing
?
Second Invocation:
CodeToRun is executing