using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication7
{
public delegate void EH(string strText); //第一步: 定义新委托类型 (类)
class EventSourse
{
public event EH Textout; //声明新委托变量 (实例变量)
public void TriggerEvent()
{
if (null != Textout)
Textout("Event Triggered"); //第三步:调用委托
}
}
class TestApp
{
static void Main(string[] args)
{
EventSourse evsrc = new EventSourse(); //实例化EventSource类
evsrc.Textout += new EH(catchEvent);//第二步:实例化evsrc.Textout----将catchEvent静态方法委托到ecsrc.Textout(实例变量)上
evsrc.TriggerEvent(); ////验证委托//调用委托代表的方法 catch
evsrc.Textout -= new EH(catchEvent);
evsrc.TriggerEvent();
TestApp theApp = new TestApp();
evsrc.Textout += new EH(theApp.instancecatch);
evsrc.TriggerEvent();
Console.Read();
}
public static void catchEvent(string strText)
{
Console.WriteLine(strText); //通过Textout(strText),其中strText="Event Triggered"调用、catchEvent,所以输出 Event Triggered
}
public void instancecatch(string strText)
{
Console.WriteLine("instance" + strText);
}
}
}