编写C#程序 有个高档的热水器,包含一个加热器,一个报警器和一个现实屏,我们给热水器它通上电,当水温超过95度的时候: 1、报警器会开始发出语音,告诉你水的温度; 2、液晶屏也会改变水温的显示,来提示水已经快烧开了。
时间: 2024-03-12 18:43:00 浏览: 20
好的,这是一个简单的C#程序示例,实现了您所说的高档热水器的功能。
```csharp
using System;
class Heater
{
private int temperature = 0; // 热水器的温度
// 温度变化时触发的事件
public event Action<int> TemperatureChanged;
// 加热器加热
public void Heat()
{
while (temperature < 95)
{
temperature++;
Console.WriteLine("当前水温:{0}", temperature);
if (temperature == 95)
{
if (TemperatureChanged != null)
{
TemperatureChanged(temperature);
}
}
}
}
}
class Alarm
{
// 温度变化时触发的事件处理方法
public void OnTemperatureChanged(int temperature)
{
Console.WriteLine("警告:水温已经达到{0}度!", temperature);
}
}
class Display
{
// 温度变化时触发的事件处理方法
public void OnTemperatureChanged(int temperature)
{
Console.WriteLine("水温:{0}", temperature);
}
}
class Program
{
static void Main(string[] args)
{
Heater heater = new Heater();
Alarm alarm = new Alarm();
Display display = new Display();
heater.TemperatureChanged += alarm.OnTemperatureChanged;
heater.TemperatureChanged += display.OnTemperatureChanged;
heater.Heat();
Console.ReadLine();
}
}
```
在这个程序中,我们定义了一个Heater类,它包含一个温度变量temperature和一个加热器Heat方法。当加热器启动时,循环逐渐增加温度,直到温度达到95度。当温度达到95度时,会触发TemperatureChanged事件。我们定义了一个Alarm类和一个Display类,它们都实现了OnTemperatureChanged方法,用于在水温达到95度时执行相应的操作。在程序的Main方法中,我们创建了一个Heater对象、一个Alarm对象和一个Display对象,并将它们的OnTemperatureChanged方法添加到Heater对象的TemperatureChanged事件中。最后,我们调用Heater对象的Heat方法,开始加热过程。当水温达到95度时,会触发TemperatureChanged事件,Alarm对象和Display对象的OnTemperatureChanged方法会被调用,分别输出相应的警告信息和水温信息。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)