首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

C#嘱托和事件

2012-08-21 
C#委托和事件委托和事件复制代码public class EventClass{// Declare the delegate type:public delegate

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

热点排行