C# —EventHandler事件传递数据
C#中传递数据的事件是 EventHandler,官方给的解释是表示当事件提供数据时处理事件的方法 ,这里我的理解是,这个事件可以传递数据,这个数据必须继承 EventArgs
例子
这里我举一个热水器的例子
热水器 有三部分 电机(线圈发热) 温度器 (显示温度) 报警器(报警)
电机 烧水
温度器 显示温度
报警器 当温度达到100度 开始报警
实现
-
温度器 显示温度。编写一个类 Temper
Temper类属性: 当前温度 、 还有两个事件。一个事件是给电机发送是否继续工作的标志, 另外一个事件是给报警器发送当前温度
前一个事件传递的是BOOL 类型的数据
后一个事件传递的是继承了** EventArgs**的数据类 TempArgs
Temper类方法: WorkShow 显示温度方法。 同时方法 触发了给电机发送工作事件 和 给报警器发送温度事件 -
电机 烧水。编写一个类 Machine
Machine 类属性: 当前工作状态、 当前功率 。
Machine 类方法: 烧水 当接受到 温度器发送的工作标志为 false 时电机停止发热, 为true 时 继续烧水。 -
报警器 报警。编写一个类 Alarmter
Alarmter类只有方法: WorkShow 报警。 当接收到温度器发送的TempArgs 类型的数据时,会判断当温度超过 100 度 会发出报警提示。
代码演示
窗体
只有三个label
代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Temper temper = new Temper(new TempArgs(5));
Machine m = new Machine();
Alarmter a = new Alarmter();
temper.SendToMachine+= m.HotWater;
temper.SendToAlarm+= a.WorkShow;
Task.Run(() =>
{
while (m.MachineState)
{
Thread.Sleep(100);
temper.currentTem.temp++;
temper.WorkShow();
this.Invoke(new Action(() =>
{
this.label1.Text= m.tip;
this.label3.Text= a.tip;
this.label2.Text= temper.tip;
}));
}
this.Invoke(new Action(() =>
{
this.label1.Text= m.tip;
this.label3.Text= a.tip;
this.label2.Text= temper.tip;
}));
});
}
}
public class TempArgs:EventArgs {
public double temp{ get; set; }
public TempArgs(double temp)
{
this.temp=temp;
}
}
public class Machine
{
public string tip { get; set; } = "";
public double work { get; set; } = 50;
public bool MachineState { get; set; } = true;
public void HotWater(object obj,bool iswork)
{
if (iswork)
{
//加热
work++;
MachineState=true;
tip =$"加热+{work}W";
Thread.Sleep(1000);
return;
}
MachineState=false;
tip ="停止加热";
}
}
public class Temper
{
public string tip { get; set; } = "";
public TempArgs currentTem;
public Temper(TempArgs currentTem)
{
this.currentTem=currentTem;
}
public event EventHandler<TempArgs> SendToAlarm;
public event EventHandler<bool> SendToMachine;
public void WorkShow()
{
string str = "当前温度为"+ currentTem.temp;
tip=str;
if (SendToAlarm!=null)
{
SendToAlarm(this, currentTem);
}
if (SendToMachine!=null)
{
if (currentTem.temp>99)
{
SendToMachine.Invoke(this, false);
return;
}
SendToMachine.Invoke(this, true);
}
}
}
public class Alarmter
{
public string tip { get; set; } = "";
public void WorkShow(object obj, TempArgs tempArgs)
{
if (tempArgs.temp>99)
{
tip="嘀嘀嘀。。。水烧开了";
}
}
}
}
结果显示
通过这个小例子学会了事件传递数据的事件使用。