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)
        }
    }
}

 

posted on 2016-09-24 15:51 jayhust 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/jayhust/p/5903403.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值