首页 > 代码库 > C#类对象的事件定义
C#类对象的事件定义
1. 类对象代码
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Timers; namespace WinformEventTest{ /// <summary> /// 定义了一个 ShowString 事件的对象类 /// </summary> internal class EventClass { /// <summary> /// 声明委托 /// </summary> /// <param name="a">委托传递的参数</param> public delegate void BroadcastEventHander(string a); /// <summary> /// 声明委托相关的事件 /// </summary> public event BroadcastEventHander Broadcast; /// <summary> /// 声明定时器 /// </summary> private Timer _timer; /// <summary> /// /// </summary> public EventClass() { _timer = new Timer(1000); _timer.Elapsed += new ElapsedEventHandler(Timer_Elapsed); _timer.Enabled = true; } /// <summary> /// 内部定时器事件,用于模拟产生事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> 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; /// <summary> /// 控制台打印字符串 /// </summary> /// <param name="a"></param> 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) } }}
C#类对象的事件定义
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。