using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace eventTest20231209
{
class Program
{
static void Main(string[] args)
{
EventClass my = new EventClass();
my.CustomEvent += new EventClass.CustomEventHandler(TestClass.CustomEvent1);
my.CustomEvent += new EventClass.CustomEventHandler(TestClass.CustomEvent2);
my.CustomEvent += new EventClass.CustomEventHandler(TestClass.CustomEvent3);
my.InvokeEvent();
System.Threading.Thread.Sleep(1000);
my.CustomEvent -= new EventClass.CustomEventHandler(TestClass.CustomEvent2);
my.InvokeEvent();
Console.ReadLine();
}
}
public class EventClass //事件的拥有者
{
//(1)声明一个委托类型
public delegate void CustomEventHandler(object sender, EventArgs e);
//(2)用委托类型声明事件
public event CustomEventHandler CustomEvent;
public void InvokeEvent()
{
if (CustomEvent != null)//判断事件是否有对象注册了
{
CustomEvent(this, EventArgs.Empty);//调用事件
}
}
}
public class TestClass
{
public static void CustomEvent1(object sender, EventArgs e)
{
Console.WriteLine("Fire Event1 is {0}", DateTime.Now);
}
public static void CustomEvent2(object sender, EventArgs e)
{
Console.WriteLine("Fire Event2 is {0}", DateTime.Now);
}
public static void CustomEvent3(object sender, EventArgs e)
{
Console.WriteLine("Fire Event3 is {0}", DateTime.Now);
}
}
}