简单示例如下
一.界面显示:
二.源代码示例:
// 定义一个委托类型,用于事件处理程序public delegate void MyEventHandler(object sender, EventArgs e);// 发布者类public class ProcessBusinessClass{// 声明事件public event MyEventHandler ProcessCompleted;// 触发事件的方法protected virtual void OnProcessCompleted(EventArgs e){ProcessCompleted?.Invoke(this, e);}// 模拟业务逻辑过程并触发事件public void StartMyEvent(){//Console.WriteLine("Process Started!");MessageBox.Show("事件触发开始");// 这里可以加入实际的运算逻辑的代码// 业务逻辑完成,触发事件OnProcessCompleted(EventArgs.Empty);}}// 订阅者类public class EventSubscriberClass{public void SubMyEvent(ProcessBusinessClass process){process.ProcessCompleted += Process_ProcessCompleted;}private void Process_ProcessCompleted(object sender, EventArgs e){MessageBox.Show("事件被执行!");}}private void DoSomething(){ProcessBusinessClass process = new ProcessBusinessClass();EventSubscriberClass subscriber = new EventSubscriberClass();// 订阅事件subscriber.SubMyEvent(process);// 启动过程process.StartMyEvent();}private void button18_Click(object sender, EventArgs e){DoSomething();}
简单示例,大家参照理解,一起学习。。。。。。