C# 事件

事件和委托极为的相似。其实,事件就好像被简化的针对特殊用途的委托。

1,发布者定义时间成员。

2,订阅者注册在事件成员被触发时要调用的方法。

3,当发布者触发事件时,所有列表注册的事件都将被调用。

下面我们来看一个简单的例子:

EventHandler是.Net BCL使用预定义的用于标准时间的委托,

public delegate void EventHandler(object sender,EventArgs e)

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

namespace EventHandlerTest
{
    class Program
    {
        //委托
        public delegate void EventHandler(string a);
        //事件
        public static event EventHandler SetCode;
        static void Main(string[] args)
        {
            //注册
            Program.SetCode += GetCode;
            //触发
            if (SetCode != null) //检查是否有事件注册
            {
                SetCode("触发");
            }
            //取消
            Program.SetCode -= GetCode;
            Console.ReadLine();
        }

        public static void GetCode(string s)
        {
            Console.WriteLine(s);
        }
    }
}

我们来看另外一个例子:

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

namespace TestEvent1
{
    public class MyTimeClass
    {
        public event EventHandler Elapsed;  //声明事件

        public void OnOneSecond(object source, EventArgs args)
        {
            if (Elapsed != null)
            {
                Elapsed(source,args);
            }
        }

        private System.Timers.Timer MyPrivateTimer;//私有计时器
       public MyTimeClass() { MyPrivateTimer = new System.Timers.Timer(); //创建私有计时器 MyPrivateTimer.Elapsed += OnOneSecond; //附加事件处理程序 MyPrivateTimer.Interval = 1000; MyPrivateTimer.Enabled = true; } } class classA { public void TimerHandlerA(object source, EventArgs args) { Console.WriteLine("****************************"); Console.WriteLine("ClassA EventHandler called"); } } class classB { public static void TimerHandlerB(object source, EventArgs args) { Console.WriteLine("ClassB EventHandler called"); Console.WriteLine("****************************"); } } class Program { static void Main(string[] args) { classA ca = new classA(); MyTimeClass mtc = new MyTimeClass(); mtc.Elapsed += ca.TimerHandlerA; mtc.Elapsed += classB.TimerHandlerB; Thread.Sleep(2000); Random random = new Random(); while (true) { int tmp = random.Next(1,3); switch (tmp) { case 1: mtc.Elapsed -= ca.TimerHandlerA; Console.WriteLine("ClassA Handler Cancled"); mtc.Elapsed += ca.TimerHandlerA; break; case 2: mtc.Elapsed -= classB.TimerHandlerB; Console.WriteLine("ClassB Handler Cancled"); mtc.Elapsed += classB.TimerHandlerB; break; default: break; } Thread.Sleep(2000); } } } }

运行结果: 

 

  PS:事件驱动的创建

private System.Timers.Timer MyPrivateTimer; //声明私有计时器变量
MyPrivateTimer = new System.Timers.Timer(); //创建私有计时器
MyPrivateTimer.Elapsed += OnOneSecond;      //附加事件处理程序
MyPrivateTimer.Interval = 1000;             //设置事件间隔
MyPrivateTimer.Enabled = true;          //启用
原文地址:https://www.cnblogs.com/wuzhang/p/wuzhang20150815.html