事件

把客户代码关联到类通知的办法——使用事件

using System;

// 向前声明
public delegate void EventHandler(string strText);

class EventSource
{
    public event EventHandler TextOut;

    public void TriggerEvent()
    {
        if (null != TextOut) TextOut("Event triggered");
    }
}

class TestApp
{
    public static void Main()
    {
        EventSource evsrc = new EventSource();

        evsrc.TextOut += new EventHandler(CatchEvent);
        evsrc.TriggerEvent();

        evsrc.TextOut -= new EventHandler(CatchEvent);
        evsrc.TriggerEvent();

        TestApp theApp = new TestApp();
        evsrc.TextOut += new EventHandler(theApp.InstanceCatch);
        evsrc.TriggerEvent();
    }

    public static void CatchEvent(string strText)
    {
        Console.WriteLine(strText);
    }

    public void InstanceCatch(string strText)
    {
        Console.WriteLine("Instance " + strText);
    }
}

EventSource 被实例化,而静态方法CatchEvent被预关联上了 TextOut事件:
evsrc.TextOut += new EventHandler(CatchEvent);
从现在起,当事件被触发时,该方法被调用。如果对事件不再感兴趣,简单地取消关联:
evsrc.TextOut -= new EventHandler(CatchEvent);

你可能感兴趣的:(事件)