对事件与委托的理解(3) 事件示例

原创 2004年10月18日 19:02:00

此处介绍的示例是建立在事件和委托和引发事件中讨论的多个部分的基础上的。
本示例显示了如何从您的类引发事件以及如何处理事件。它定义了以下类。
AlarmClock 是引发 Alarm 事件的类。
AlarmEventArgs 为 Alarm 事件定义数据。
AlarmEventHandler 是 Alarm 事件的委托。
WakeMeUp 是具有 AlarmRang 方法的类,该方法处理 Alarm 事件。
AlarmDriver 是示范事件如何连结的类。该类实例化 AlarmClock 和 WakeMeUp。然后,该类通过对 WakeMeUp 实例的 AlarmRang 方法的引用实例化 AlarmEventHandler 委托。AlarmDriver 通过向 AlarmClock 的实例注册该委托并用 += 语法将委托添加到一个事件,完成事件连结。
编译和运行该示例
将以下代码复制到源文件(如 EventSample.cs 或 EventSample.vb)。
从包含源文件的目录下,执行下列命令:
[C#]
csc /r:System.dll EventSample.cs

[Visual Basic]
vbc /r:System.dll EventSample.vb
(/r 选项引用 System 程序集。)
运行创建的可执行文件 EventSample.exe。
[C#]
// EventSample.cs.
//
namespace EventSample

   using System;
   using System.ComponentModel;
  
   // Class that contains the data for
   // the alarm event. Derives from System.EventArgs.
   //
   public class AlarmEventArgs : EventArgs
   { 
      private readonly bool snoozePressed ;
      private readonly int nrings;
     
      //Constructor.
      //
      public AlarmEventArgs(bool snoozePressed, int nrings)
      {
         this.snoozePressed = snoozePressed;
         this.nrings = nrings;
      }
     
      // The NumRings property returns the number of rings
      // that the alarm clock has sounded when the alarm event
      // is generated.
      //
      public int NumRings
      {    
         get { return nrings;}     
      }
     
      // The SnoozePressed property indicates whether the snooze
      // button is pressed on the alarm when the alarm event is generated.
      //
      public bool SnoozePressed
      {
         get {return snoozePressed;}
      }
     
      // The AlarmText property that contains the wake-up message.
      //
      public string AlarmText
      {
         get
         {
            if (snoozePressed)
            {
               return ("Wake Up!!! Snooze time is over.");
            }
            else
            {
               return ("Wake Up!");
            }
         }
      } 
   }
  
   // Delegate declaration.
   //
   public delegate void AlarmEventHandler(object sender, AlarmEventArgs e);
  
   // The Alarm class that raises the alarm event.
   //
   public class AlarmClock
   { 
      private bool snoozePressed = false;
      private int nrings = 0;
      private bool stop = false;
     
      // The Stop property indicates whether the
      // alarm should be turned off.
      //
      public bool Stop
      {
         get {return stop;}
         set {stop = value;}
      }
     
      // The SnoozePressed property indicates whether the snooze
      // button is pressed on the alarm when the alarm event is generated.
      //
      public bool SnoozePressed
      {
         get {return snoozePressed;}
         set {snoozePressed = value;}
      }
   // The event member that is of type AlarmEventHandler.
      //
      public event AlarmEventHandler Alarm;

      // The protected OnAlarm method raises the event by invoking
      // the delegates. The sender is always this, the current instance
      // of the class.
      //
      protected virtual void OnAlarm(AlarmEventArgs e)
      {
         if (Alarm != null)
         {
            // Invokes the delegates.
            Alarm(this, e);
         }
      }
     
      // This alarm clock does not have
      // a user interface.
      // To simulate the alarm mechanism it has a loop
      // that raises the alarm event at every iteration
      // with a time delay of 300 milliseconds,
      // if snooze is not pressed. If snooze is pressed,
      // the time delay is 1000 milliseconds.
      //
      public void Start()
      {
         for (;;)   
         {
            nrings++;     
            if (stop)
            {
               break;
            }
           
            else if (snoozePressed)
            {
               System.Threading.Thread.Sleep(1000);
               {
                  AlarmEventArgs e = new AlarmEventArgs(snoozePressed,
                     nrings);
                  OnAlarm(e);
               }
            }
            else
            {
               System.Threading.Thread.Sleep(300);
               AlarmEventArgs e = new AlarmEventArgs(snoozePressed,
                  nrings);
               OnAlarm(e);
            }          
         }
      }
   }
  
   // The WakeMeUp class that has a method AlarmRang that handles the
   // alarm event.
   //
   public class WakeMeUp
   {
     
      public void AlarmRang(object sender, AlarmEventArgs e)
      {
        
         Console.WriteLine(e.AlarmText +"/n");
        
         if (!(e.SnoozePressed))
         {
            if (e.NumRings % 10 == 0)
            {
               Console.WriteLine(" Let alarm ring? Enter Y");
               Console.WriteLine(" Press Snooze? Enter N");
               Console.WriteLine(" Stop Alarm? Enter Q");
               String input = Console.ReadLine();
              
               if (input.Equals("Y") ||input.Equals("y")) return;
              
               else if (input.Equals("N") || input.Equals("n"))
               {
                  ((AlarmClock)sender).SnoozePressed = true;
                  return;
               }
               else
               {
                  ((AlarmClock)sender).Stop = true;
                  return;
               }
            }
         }
         else
         {
            Console.WriteLine(" Let alarm ring? Enter Y");
            Console.WriteLine(" Stop Alarm? Enter Q");
            String input = Console.ReadLine();
            if (input.Equals("Y") || input.Equals("y")) return;
            else
            {
               ((AlarmClock)sender).Stop = true;
               return;
            }
         }
      }
   }
  
  
  
   // The driver class that hooks up the event handling method of
   // WakeMeUp to the alarm event of an Alarm object using a delegate.
   // In a forms-based application, the driver class is the
   // form.
   //
   public class AlarmDriver
   { 
      public static void Main (string[] args)
      { 
         // Instantiates the event receiver.
         WakeMeUp w= new WakeMeUp();
                 
         // Instantiates the event source.
         AlarmClock clock = new AlarmClock();

         // Wires the AlarmRang method to the Alarm event.
         clock.Alarm += new AlarmEventHandler(w.AlarmRang);

         clock.Start();
      }
   }  
}
[Visual Basic]
' EventSample.vb.
'
Option Explicit
Option Strict

Imports System
Imports System.ComponentModel
Imports Microsoft.VisualBasic

Namespace EventSample
  
   ' Class that contains the data for
   ' the alarm event. Derives from System.EventArgs.
   '
   Public Class AlarmEventArgs
      Inherits EventArgs
      Private _snoozePressed As Boolean
      Private nrings As Integer
     
      'Constructor.
      '
      Public Sub New(snoozePressed As Boolean, nrings As Integer)
         Me._snoozePressed = snoozePressed
         Me.nrings = nrings
      End Sub
     
      ' The NumRings property returns the number of rings
      ' that the alarm clock has sounded when the alarm event
      ' is generated.
      '
      Public ReadOnly Property NumRings() As Integer
         Get
            Return nrings
         End Get
      End Property
     
      ' The SnoozePressed property indicates whether the snooze
      ' button is pressed on the alarm when the alarm event is generated.
      '
      Public ReadOnly Property SnoozePressed() As Boolean
         Get
            Return _snoozePressed
         End Get
      End Property
     
      ' The AlarmText property that contains the wake-up message.
      '
      Public ReadOnly Property AlarmText() As String
         Get
            If _snoozePressed Then
               Return "Wake Up!!! Snooze time is over."
            Else
               Return "Wake Up!"
            End If
         End Get
      End Property
   End Class
  
  
   ' Delegate declaration.
   '
   Public Delegate Sub AlarmEventHandler(sender As Object, e As AlarmEventArgs)

   ' The Alarm class that raises the alarm event.
   '
   Public Class AlarmClock
      Private _snoozePressed As Boolean = False
      Private nrings As Integer = 0
      Private stopFlag As Boolean = False
     
      ' The Stop property indicates whether the
      ' alarm should be turned off.
      '
      Public Property [Stop]() As Boolean
         Get
            Return stopFlag
         End Get
         Set
            stopFlag = value
         End Set
      End Property
     
      ' The SnoozePressed property indicates whether the snooze
      ' button is pressed on the alarm when the alarm event is generated.
      '
      Public Property SnoozePressed() As Boolean
         Get
            Return _snoozePressed
         End Get
         Set
            _snoozePressed = value
         End Set
      End Property

      ' The event member that is of type AlarmEventHandler.
      '
      Public Event Alarm As AlarmEventHandler
     
      ' The protected OnAlarm method raises the event by invoking
      ' the delegates. The sender is always this, the current instance
      ' of the class.
      '
      Protected Overridable Sub OnAlarm(e As AlarmEventArgs)
         RaiseEvent Alarm(Me, e)
      End Sub
     
     
      ' This alarm clock does not have
      ' a user interface.
      ' To simulate the alarm mechanism it has a loop
      ' that raises the alarm event at every iteration
      ' with a time delay of 300 milliseconds,
      ' if snooze is not pressed. If snooze is pressed,
      ' the time delay is 1000 milliseconds.
      '
      Public Sub Start()
         Do
            nrings += 1
            If stopFlag Then
               Exit Do
           
            Else
               If _snoozePressed Then
                  System.Threading.Thread.Sleep(1000)
                  If (True) Then
                     Dim e As New AlarmEventArgs(_snoozePressed, nrings)
                     OnAlarm(e)
                  End If
               Else
                  System.Threading.Thread.Sleep(300)
                  Dim e As New AlarmEventArgs(_snoozePressed, nrings)
                  OnAlarm(e)
               End If
            End If
         Loop
      End Sub
   End Class
 
   ' The WakeMeUp class that has a method AlarmRang that handles the
   ' alarm event.
   '
   Public Class WakeMeUp
      Public Sub AlarmRang(sender As Object, e As AlarmEventArgs)
        
         Console.WriteLine((e.AlarmText + ControlChars.Cr))
        
         If Not e.SnoozePressed Then
            If e.NumRings Mod 10 = 0 Then
               Console.WriteLine(" Let alarm ring? Enter Y")
               Console.WriteLine(" Press Snooze? Enter N")
               Console.WriteLine(" Stop Alarm? Enter Q")
               Dim input As String = Console.ReadLine()
              
               If input.Equals("Y") Or input.Equals("y") Then
                  Return
              
               Else
                  If input.Equals("N") Or input.Equals("n") Then
                     CType(sender, AlarmClock).SnoozePressed = True
                     Return
                  Else
                     CType(sender, AlarmClock).Stop = True
                     Return
                  End If
               End If
            End If
         Else
            Console.WriteLine(" Let alarm ring? Enter Y")
            Console.WriteLine(" Stop Alarm? Enter Q")
            Dim input As String = Console.ReadLine()
            If input.Equals("Y") Or input.Equals("y") Then
               Return
            Else
               CType(sender, AlarmClock).Stop = True
               Return
            End If
         End If
      End Sub
   End Class
  
   ' The driver class that hooks up the event handling method of
   ' WakeMeUp to the alarm event of an Alarm object using a delegate.
   ' In a forms-based application, the driver class is the
   ' form.
   '
   Public Class AlarmDriver
      Public Shared Sub Main()
         ' Instantiates the event receiver.
         Dim w As New WakeMeUp()
        
         ' Instantiates the event source.
         Dim clock As New AlarmClock()
        
         ' Wires the AlarmRang method to the Alarm event.
         AddHandler clock.Alarm, AddressOf w.AlarmRang
        
         clock.Start()
      End Sub
   End Class
End Namespace

快速理解C#中的委托与事件

以下内容只是个人理解,仅供参考。 什么是委托? 先看最简单的委托例子: namespace DelegateTest { public delegate void MessageDele...
  • Wiiix
  • Wiiix
  • 2016年05月20日 20:02
  • 5608

委托和事件的区别(讲的很详细)

原文地址:http://www.tracefact.net/CSharp-Programming/Delegates-and-Events-in-CSharp.aspx 委托 和 事件在 .Net F...
  • chopper7278
  • chopper7278
  • 2008年10月25日 23:58
  • 12384

事件与委托趣谈

 事件与委托似乎很难以理解,这是因为它们的使用方式与常用的编码有很大的差别,例如通常编写的都是同步代码,调用一个类型的方法,会即刻出现方法执行的结果,这是符合逻辑的。但在某些情况中,同步代码未必满足需...
  • chiangbt
  • chiangbt
  • 2008年01月17日 21:51
  • 26587

通过一个WPF实例进一步理解委托和事件

在前写过“浅谈C#中的委托”和“浅谈C#中的事件”两篇博客,内容有些抽象,似乎难以说明委托和事件的关系。 今天通过一个小程序来进一步说明二者的使用及联系。 首先新建一个WPF应用程序,取名TestDe...
  • wangshubo1989
  • wangshubo1989
  • 2015年08月26日 16:39
  • 3848

【C#】C#委托和事件的实例讲解

using System; namespace delegate_event { // 定义一个猫类 class Cat { // 定义一个名字字段 private string na...
  • sinat_20559947
  • sinat_20559947
  • 2015年07月22日 15:33
  • 4025

C# .Net 委托和事件的区别

   在.net中,事件是一种特殊的委托,那他到底特殊在哪,换句话说,加上event关键字到底有什么用,我理解主要有两方面,下面用实例说明:    一 、事件只能在本类型内部“触发”,委托不管在本类型...
  • azkaser
  • azkaser
  • 2009年11月24日 15:18
  • 8884

观察者设计模式 Vs 事件委托(java)

观察者设计模式 Vs 事件委托标签: 设计模式 java 事件的委托本篇博客主要讲解一下几个问题 什么是观察者模式 观察者模式的优缺点 如何看待观察者模式的缺点 事件的委托 什么是观察...
  • gdutxiaoxu
  • gdutxiaoxu
  • 2016年07月05日 00:03
  • 6129

C#委托、事件学习之(三)——热水器烧水案例

using System; namespace DelegateExample { public class Heater { private int tempera...
  • lucky51222
  • lucky51222
  • 2015年09月14日 11:17
  • 2458

CSharp学习笔记之十一 委托与事件

对C#的委托和事件,其实想写点东西,但是偶然间翻到一篇文章,感觉挺好的,所以就直接转过来吧。其实好的东西都是要用来分享的么,不管是不是我自己的,但是学会了,就是我自己的。学习么就是这样的,这篇博文不算...
  • caosiyuan1991
  • caosiyuan1991
  • 2013年12月27日 16:26
  • 4422

Unity中对于委托、事件的应用

[引言] 这边文章主要是针对刚踏入这行的程序员,是我工作半年多来积累下来的一些经验,仅作为参考,也希望各位经验丰富的前辈多批评指正。 我是专科生毕业,我们学校所教的C#的内容其实只有非常非常基础的那些...
  • GhostOrange
  • GhostOrange
  • 2016年11月13日 18:01
  • 2363
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:对事件与委托的理解(3) 事件示例
举报原因:
原因补充:

(最多只允许输入30个字)