简单示例如下
一.界面显示:
二.源代码示例:
// 定义一个委托类型,用于事件处理程序
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();
}
简单示例,大家参照理解,一起学习。。。。。。
标签:C#,void,EventArgs,public,process,事件,应用,Event,ProcessCompleted From: https://blog.csdn.net/weixin_53520014/article/details/142589343