#region 委托与事件 闹钟小实例
/*
* 包含:
* Prpgram类
* AlarmClock 实体类
* BellEventArgs 闹铃事件参数类
*
* 作者:大元帅
* QQ:593658550
* 时间:2019年8月1日
* 参考博客地址:https://www.cnblogs.com/guolihao/archive/2012/07/26/2609944.html
*/
#endregion
using System;
using System.Speech.Synthesis;
namespace 委托事件小实例_闹钟
{
class Program
{
static void Main(string[] args)
{
AlarmClock alarmClock = new AlarmClock();
alarmClock.SetBellTime(22,9,30);
alarmClock.BellEvent += new BellEventHandler(BellTrigger);
alarmClock.StartBell();
}
private static void BellTrigger(object sender, BellEventArgs e)
{
string bellMsg = string.Format("{0}时{1}分{2}秒-->{3}", e.Hour, e.Minute, e.Second, e.BellWord);
Console.WriteLine(bellMsg);
using (SpeechSynthesizer speechSynthesizer=new SpeechSynthesizer())
{
speechSynthesizer.SetOutputToDefaultAudioDevice();
speechSynthesizer.Speak(bellMsg);
}
Console.Read();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 委托事件小实例_闹钟
{
public delegate void BellEventHandler(object sender,BellEventArgs e);
///
/// 闹铃事件参数类
///
public class BellEventArgs:EventArgs
{
public int Hour { get; }
public int Minute { get; }
public int Second { get; }
public string BellWord { get; }
public BellEventArgs(int hour,int minute,int second,string bellWord)
{
Hour = hour;
Minute = minute;
Second = second;
BellWord = bellWord;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 委托事件小实例_闹钟
{
///
/// 闹钟实体类
///
public class AlarmClock
{
private int Hour = 0;
private int Minute = 0;
private int Second = 0;
public event BellEventHandler BellEvent;
public void StartBell()
{
while (!(DateTime.Now.Hour==Hour&&DateTime.Now.Minute==Minute&&DateTime.Now.Second==Second))
{
}
BellEventArgs bellEventArgs = new BellEventArgs(Hour, Minute, Second, "大懒虫起床了。。6666");
BellEvent(this,bellEventArgs);
}
///
///
///
///
///
///
///
public bool SetBellTime(int _h, int _m, int _s)
{
if (_h > 24)
{
return false;
}
if (_m > 60)
{
return false;
}
if (_s > 60)
{
return false;
}
Hour = _h;
Minute = _m;
Second = _s;
return true;
}
}
}