参考书目:C#6.0学习笔记——从第一行C#代码到第一个项目设计(作者周家安)
学习目的:掌握事件与委托的用法,定义一个委托类型,作为响应按下空格键这一事件。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace Example3_14
{
//定义一个委托类型,作为响应按下空格键这一事件
public delegate void SpacekeyPressedEventHandler();
//定义一个MyApp类,包含字段,方法
public class MyApp
{
//声明事件
public event SpacekeyPressedEventHandler SpaceKeyPressed;
//通过以下方法调用事件,是一个虚函数
protected virtual void OnSpaceKeyPressed()
{
if(this.SpaceKeyPressed != null) //事件出现时
{
SpaceKeyPressed(); //调用响应函数
}
// 下面代码与上面的if一段代码是等效的
// this.SpaceKeyPressed?.Invoke();
}
public void StartRun()
{
while(true)
{
ConsoleKeyInfo keyinfo = ReadKey(); //读入按键输入
if(keyinfo.Key == ConsoleKey.Spacebar) //如果按下的是空格键
{
//引发事件
OnSpaceKeyPressed();
}
if (keyinfo.Key == ConsoleKey.Escape) //如果按下的是返回键
{
//跳出循环
break;
}
}
}
}
class Program
{
static void Main(string[] args)
{
MyApp app = new MyApp(); //定义一个MyApp对象
app.SpaceKeyPressed += app_SpaceKeyPressed;
app.StartRun();
}
static void app_SpaceKeyPressed()
{
Console.WriteLine("{0}按下空格键。", DateTime.Now.ToLongTimeString());
}
}
}
运行结果如下: