namespace controldelegate
{
/// <summary>
/// 事件发送者,可以触发事件
/// </summary>
public delegate void eventsendereventhandler(string strtext);
public class eventsender:system.eventargs
{
public eventsender()
{
//相当于一个安纽类,这在winform中
//类的具体是不用我们实现的了,我们只管继承就可以了
}
public event eventsendereventhandler textout;
public void ontextout()
{
if(null!=textout)
{
textout("事件点火了");
return;
}
console.writeline("事件没被预定");
}
}
/// <summary>
/// 事件的接收者,捕捉事件,并做出响应
/// </summary>
public class eventreceiver
{
public eventreceiver()
{
//我们通常编的winform程序好象都是做为消息接收者程序
//而消息发送者该是windows本身吧
}
public static void main()
{
eventsender sender=new eventsender();//相当于一个安纽类
sender.textout+=new eventsendereventhandler(eventreceiver.staticcatchevent);
sender.ontextout();
sender.textout-=new eventsendereventhandler(eventreceiver.staticcatchevent);
sender.ontextout();
eventreceiver receiver=new eventreceiver();
sender.textout+=new eventsendereventhandler(receiver.instancecatchevent);
sender.ontextout();//相当于我们点击某个按纽吧
console.readline();
}
public static void staticcatchevent(string strtext)
{
console.writeline(strtext);
}
public void instancecatchevent(string strtext)
{
console.writeline("实例的"+strtext);
}
}
}
执行顺序:
main()
建立了发送者和接受者之间的关系
接受者响应发送者的textout事件,并用自己的
staticcatchevent()
和
instancecatchvent()
去处理发送者的textout事件
当我们调用ontextout去激活发送者事件时
消息发送者会寻找谁对我的这个事件感兴趣
找到了是消息接受者eventreceiver的一个方法
ok! 这个方法就被调用了
(注意呀,
这个方法的模式和消息发送者的事件的模式是一样的了)
哈哈
我也是自己说的这些
一定有不妥的地方
希望指正
