Visual Studio EventHandler Delegate 和 EventArgs

本文介绍.NET中事件处理的基础概念及使用EventHandler委托的具体实例。通过一个计数器类的示例展示了如何定义事件、触发事件及事件监听的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

EventHandler代理 用来表示处理一个没有事件数据(event data)的事件(event)的 方法。

无论何时事件发生时,事件代理就被调用来触发以前事件驱动的其他事件(监听当前事件TCurrentEvent += TListenerEvent)。

public delegate void EventHandler(
	Object sender,    //事件发起者
	EventArgs e       //处理事件数据的对象
)

 

EventArgs 类是事件变量的基类,提供事件数据类型给某个事件。

System.Object 
  System.EventArgs
    More...

public class EventArgs  

 

The following example shows an event named ThresholdReached that is associated with an EventHandler delegate. The method assigned to the EventHandler delegate is called in the OnThresholdReached method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace delegrate
{
    class Program
    {
        static void Main(string[] args)
        {
            Counter c = new Counter(new Random().Next(10));
            c.ThresholdReached += c_ThresholdReached;  //声明一个事件监听

            Console.WriteLine("press 'a' key to increase total");
            while (Console.ReadKey(true).KeyChar == 'a')
            {
                Console.WriteLine("adding one");  
                c.Add(1);    
            }
        }

        static void c_ThresholdReached(object sender, ThresholdReachedEventArgs e)
        {
            Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached);
            Environment.Exit(0);
        }
    }

    class Counter
    {
        private int threshold;
        private int total;

        public Counter(int passedThreshold)
        {
            threshold = passedThreshold;
        }

        public void Add(int x)
        {
            total += x;
            if (total >= threshold)
            {
                ThresholdReachedEventArgs args = new ThresholdReachedEventArgs();
                args.Threshold = threshold;
                args.TimeReached = DateTime.Now;
                OnThresholdReached(args);          //传输一个 TEventArgs-->ThresholdReachedEventArgs
            }
        }

        protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
        {
            EventHandler<ThresholdReachedEventArgs> handler = ThresholdReached;  //handle an Event
            if (handler != null)
            {
                handler(this, e);   //触发 c_ThresholdReached
            }
        }

        public event EventHandler<ThresholdReachedEventArgs> ThresholdReached;
    }
       
    public class ThresholdReachedEventArgs : EventArgs
    {
        public int Threshold { get; set; }
        public DateTime TimeReached { get; set; }
    }
}

  

转载于:https://www.cnblogs.com/bruceyo/p/3900541.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值