首页 > 代码库 > 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#类对象的事件定义