.net自定义事件示例分享

  1、新建一个控制台应用程序TestDelegate,本项目主要实现:热水器加热,报警器监控,当热水温度达到80度的时候报警器报警这样一个简单的事件处理程序

  2、定义委托处理程序

  

复制代码 代码如下:

  public delegate void PlayGameHandler(object sender, System.EventArgs e);

  3、添加一个报警器类,报警方法只有在温度超过80度的时候会被调用

  

复制代码 代码如下:

  // 负责报警的人

  public class 报警器

  {

  public 报警器()

  {

  Console.WriteLine("生成报警器...");

  }

  public void 报警(object sender, EventArgs e)

  {

  System.Threading.Thread.Sleep(100);//休息0.1秒

  Console.WriteLine("滴滴。。。。温度超过80度...");

  }

  }

  4、添加一个热水器类,利用循环加热热水器,从一度增加到100度,当温度超过80度时候触发事件报警

  

复制代码 代码如下:

  // 如果加热,则引发事件

  public class 热水器

  {

  // 先定义一个事件,这个事件表示“热水器”在加热。

  public event PlayGameHandler PlayGame;

  public 热水器()

  {

  Console.WriteLine("生成热水器....");

  }

  public void 加热()

  {

  Console.WriteLine("开始加热了.....");

  System.EventArgs e = new EventArgs();

  for (int i = 1; i < 101;i++)//温度每增加一度调触发一次事件

  {

  System.Threading.Thread.Sleep(100);//休息0.1秒

  Console.WriteLine(i.ToString()+"度");

  if (PlayGame != null)

  {

  if(i>=80)//当温度大于80度

  PlayGame(this, e);//触发事件

  }

  }

  }

  }

  5、客户端开始调用

  

复制代码 代码如下:

  public class Program

  {

  //[STAThread]

  public static void Main(string[] args)

  {

  Console.WriteLine("场景开始了....");

  报警器 w = new 报警器();

  热水器 z = new 热水器();

  // 指定监视

  z.PlayGame += new PlayGameHandler(w.报警);

  System.Threading.Thread.Sleep(1000);

  // 开始加热

  z.加热();

  Console.WriteLine("场景结束...");

  Console.ReadLine();

  }

  }

.net自定义事件示例分享

  大家运行一下可以看到更多数据显示