读书人

C#嘱托和事件

发布时间: 2012-08-21 13:00:22 作者: rapoo

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

读书人网 >C#

热点推荐