1. 类对象代码
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Timers; namespace WinformEventTest{ ////// 定义了一个 ShowString 事件的对象类 /// internal class EventClass { ////// 声明委托 /// /// 委托传递的参数 public delegate void BroadcastEventHander(string a); ////// 声明委托相关的事件 /// public event BroadcastEventHander Broadcast; ////// 声明定时器 /// private Timer _timer; ////// /// public EventClass() { _timer = new Timer(1000); _timer.Elapsed += new ElapsedEventHandler(Timer_Elapsed); _timer.Enabled = true; } ////// 内部定时器事件,用于模拟产生事件 /// /// /// void Timer_Elapsed(object sender, ElapsedEventArgs e) { try { Broadcast("来自 EventClass 对象事件的消息:" + DateTime.Now.ToString()); // 产生事件 } catch (Exception) { } } }}
2.Winform调用举例
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;namespace WinformEventTest{ public partial class Form1 : Form { // 声明变量 EventClass _eventClass; ////// 控制台打印字符串 /// /// public void ConsoleShowTxt(string a) { Console.WriteLine(DateTime.Now.ToString() + " | " + a + "\n"); } public Form1() { InitializeComponent(); // Member initialize _eventClass = new EventClass(); // Member event initialize _eventClass.Broadcast += new EventClass.BroadcastEventHander(ConsoleShowTxt); // 委托类事件(Broadcast)绑定实际处理方法(ConsoleShowTxt) } }}
posted on 2016-09-24 15:51 阅读( ...) 评论( ...)