Udostępnij za pośrednictwem


Jak: wdrożenie zdarzenia w klasie

Poniższe procedury opisują sposób implementacji zdarzenia w klasie. Pierwsza procedura implementuje zdarzenie, które nie ma skojarzonych danych; korzysta z klas System.EventArgs i System.EventHandler danych oraz delegowanie obsługi zdarzenia. Druga procedura implementuje zdarzenia z niestandardowymi danymi; Definiuje ona niestandardowych klas dla danych zdarzenia i obsługi zdarzeń obiektu delegowanego.

Uwaga

W tym temacie przedstawiono sposób zadeklarować i wygenerować zdarzenie w klasie.Pokazuje on jak definiuje obsługi zdarzenia, który używa tego zdarzenia.Aby uzyskać informacje na temat zużywają zdarzeń, zobacz Używające zdarzeń i Jak: podnoszenie i zużywają zdarzeń.

Kompletny przykład ilustruje podnoszenie i obsługa zdarzeń, zobacz Jak: podnoszenie i zużywają zdarzeń.

Aby zaimplementować zdarzenie bez danych specyficznej dla zdarzenia

  1. Definiowanie Członkowskie zdarzenie publiczne w klasie. Ustaw typ członka zdarzeń do System.EventHandler delegować.

    Public Class Countdown
        ' ...
    
        Public Event CountdownCompleted As EventHandler
    End Class
    
    public class Countdown 
    {
        // ...
    
        public event EventHandler CountdownCompleted;   
    }
    
  2. Zapewniają chronionych metoda w klasie, który wywołuje zdarzenie. Nazwa metody naEventName. Podnoszenie zdarzenia w ramach metody. Należy zauważyć, że kod C# należy sprawdzić, czy zdarzenie jest null, przed powodującemu zdarzenie. Eliminuje to konieczność obsługi NullReferenceException , jest generowany, gdy zdarzenie jest wywoływane, ale nie obsługi zdarzeń zostały dołączone do niego. Ten test jest konieczne w tym przypadku, ponieważ CountDown klasy po prostu wywołuje zdarzenie, ale nie zapewnia obsługi dla niego.

    Public Class Countdown
       ' ...
    
       Public Event CountdownCompleted As EventHandler
    
       Protected Overridable Sub OnCountdownCompleted(e As EventArgs)
          RaiseEvent CountdownCompleted(Me, e)
       End Sub
    End Class
    
    public class Countdown 
    {
        public event EventHandler CountdownCompleted;   
    
        protected virtual void OnCountdownCompleted(EventArgs e)
        {
            if (CountdownCompleted != null)
                CountdownCompleted(this, e);
        }
    }
    
  3. Określają, kiedy zdarzenie w klasie. Wywołanie naEventName do pozyskania zdarzenia.

    Public Class Countdown
       Dim internalCounter As Integer = 0
        ' ...
    
       Public Event CountdownCompleted As EventHandler
    
       Protected Overridable Sub OnCountdownCompleted(e As EventArgs)
          RaiseEvent CountdownCompleted(Me, e)
       End Sub
    
       Public Sub Decrement()
          internalCounter -= 1
          If internalCounter = 0
             OnCountdownCompleted(New EventArgs())
          End If
       End Sub
    End Class
    
    public class Countdown 
    {
       int internalCounter = 0;
       // ...
    
       public event EventHandler CountdownCompleted;   
    
        protected virtual void OnCountdownCompleted(EventArgs e)
        {
            if (CountdownCompleted != null)
                CountdownCompleted(this, e);
        }
    
       public void Decrement()
       {
          internalCounter--;
          if (internalCounter == 0)
             OnCountdownCompleted(new EventArgs());
       }
    }
    

Aby zaimplementować zdarzenia z danymi specyficznej dla zdarzenia

  1. Definiowanie klasy, która dostarcza dane dla tego zdarzenia. Nazwa klasy EventNameArgs, klasę z System.EventArgs, i Dodaj członków specyficznej dla zdarzenia.

    Public Class AlarmEventArgs : Inherits EventArgs
       Private nRings As Integer = 0
       Private pressed As Boolean = False
       Private text As String = "The alarm is ringing!"
    
       ' Constructor.
       Public Sub New(ByVal snoozePressed As Boolean, ByVal nRings As Integer) 
          Me.pressed = snoozePressed
          Me.nRings = nRings
       End Sub
    
       ' Properties.
       Public Property AlarmText() As String
          Get
             Return Me.text
          End Get
          Set
             Me.text = value
          End Set  
       End Property 
    
       Public ReadOnly Property NumRings() As Integer
          Get
             Return Me.nRings
          End Get   
       End Property 
    
       Public ReadOnly Property SnoozePressed() As Boolean
          Get
             Return Me.pressed
          End Get
       End Property
    End Class
    
    public class AlarmEventArgs : EventArgs 
    {
       private readonly int nRings = 0;
       private readonly bool pressed = false;
       private string text = "The alarm is ringing!";
    
       // Constructor.
       public AlarmEventArgs(bool snoozePressed, int nRings) 
       {
          this.pressed = snoozePressed;
          this.nRings = nRings;
       }
    
       // Properties.
       public string AlarmText {  
          get { return text; }
          set { this.text = value; }
       }
    
       public int NumRings {
          get { return nRings; }
       }
    
       public bool SnoozePressed {
          get { return pressed; }
       }
    }
    
  2. Zadeklarować delegata zdarzenia. Nazwa pełnomocnika EventNameEventHandler.

    Public Delegate Sub AlarmEventHandler(sender As Object, e As AlarmEventArgs)
    
    public delegate void AlarmEventHandler(object sender, AlarmEventArgs e);
    
  3. Definiowanie zdarzenie publiczne Członka o nazwie EventName w klasie. Ustaw typ członka zdarzenia typ delegata zdarzenia.

    Public Class AlarmClock
        ' ...
        Public Event Alarm As AlarmEventHandler
    
    End Class
    
    public class AlarmClock 
    {
        // ...
        public event AlarmEventHandler Alarm;
    
    }
    
  4. Definiowanie chronionych metoda w klasie, który wywołuje zdarzenie. Nazwa metody naEventName. Podnoszenie zdarzenia w ramach metody. Należy zauważyć, że kod C# należy sprawdzić, czy zdarzenie jest null, przed powodującemu zdarzenie. Eliminuje to konieczność obsługi NullReferenceException , jest generowany, gdy zdarzenie jest wywoływane, ale nie obsługi zdarzeń zostały dołączone do niego. Ten test jest konieczne w tym przypadku, ponieważ CountDown klasy po prostu wywołuje zdarzenie, ale nie zapewnia obsługi dla niego.

    Public Class AlarmClock
    
        ' ...
        Public Event Alarm As AlarmEventHandler
    
        Protected Overridable Sub OnAlarm(e As AlarmEventArgs)
            RaiseEvent Alarm(Me, e)
        End Sub
    End Class
    
    public class AlarmClock 
    {
        // ...
        public event AlarmEventHandler Alarm;
    
        protected virtual void OnAlarm(AlarmEventArgs e)
        {
          if (Alarm != null) 
              Alarm(this, e); 
        }
    }
    
  5. Określają, kiedy zdarzenie w klasie. Wywołanie naEventName zdarzenie i przekazywania danych specyficznej dla zdarzenia, przez za pomocą EventNameEventArgs.

    Public Class AlarmClock
    
        Public Sub Start
            ' ...
            System.Threading.Thread.Sleep(300)
            Dim e As AlarmEventArgs = New AlarmEventArgs(False, 0)
            OnAlarm(e)
        End Sub
    
        Public Event Alarm As AlarmEventHandler
    
        Protected Overridable Sub OnAlarm(e As AlarmEventArgs)
            RaiseEvent Alarm(Me, e)
        End Sub
    End Class
    
    public class AlarmClock 
    {
        public void Start()
        {
            // ...
            System.Threading.Thread.Sleep(300);
            AlarmEventArgs e = new AlarmEventArgs(false, 0);
            OnAlarm(e);
        }
    
        public event AlarmEventHandler Alarm;
    
        protected virtual void OnAlarm(AlarmEventArgs e)
        {
          if (Alarm != null) 
              Alarm(this, e); 
        }
    }
    

Przykład

Poniższy przykład definiuje DiskSpaceMonitor klasy, która używa zdarzenia do wyprodukowania ostrzeżenie w każdym przypadku, gdy ilość wolnego miejsca spadnie poniżej wartość procentową, która jest zdefiniowana w pliku konfiguracyjnym. Definiuje również DiskSpaceWarningEventArgs klasy zapewnienie niestandardowych danych dotyczących wolnego miejsca na dysku do obsługi zdarzeń.

Imports System.Collections.Specialized
Imports System.Configuration
Imports System.IO

Public Class DiskSpaceWarningEventArgs : Inherits EventArgs
   Dim currentFreeSpace As Long
   Dim currentTotalSpace As Long
   Dim driveName As String

   Public Sub New(name As String, freeSpace As Long, totalSpace As Long)
      Me.driveName = name
      Me.currentFreeSpace = freeSpace
      Me.currentTotalSpace = totalSpace
   End Sub

   Public ReadOnly Property Name As String
      Get
         Return Me.driveName
      End Get
   End Property

   Public ReadOnly Property FreeSpace As Long
      Get
         Return Me.currentFreeSpace 
      End Get
   End Property

   Public ReadOnly Property TotalSpace As Long
      Get
         Return Me.currentTotalSpace
      End Get
   End Property
End Class

Public Delegate Sub DiskSpaceWarningEventHandler(sender As Object, _
                                                 e As DiskSpaceWarningEventArgs)

Public Class DiskSpaceMonitor
   Public Event DiskSpaceWarning As DiskSpaceWarningEventHandler
   Private threshhold As Decimal 

   Public Sub New()
      ' Retrieve threshhold to fire event from configuration file.
      Try
         Dim settings As NameValueCollection = ConfigurationManager.AppSettings
         Me.threshhold = CDec(settings.Item("Threshhold"))
      ' If there is no configuration file, provide a default value.
      Catch e As ConfigurationErrorsException
         Me.threshhold = 10d
      Catch e As InvalidCastException
         Me.threshhold = 10d
      End Try               
   End Sub

   Public Sub CheckFreeSpace
      ' Get drives present on system.
      Dim drives() As DriveInfo = DriveInfo.GetDrives()
      For Each drive As DriveInfo In drives
         If drive.IsReady Then
            If drive.TotalFreeSpace/drive.TotalSize <= Me.threshhold Then
               OnDiskSpaceWarning(New DiskSpaceWarningEventArgs(drive.Name, _
                                  drive.TotalFreeSpace, drive.TotalSize))
            End If
         End If
      Next   
   End Sub

   Protected Sub OnDiskSpaceWarning(e As DiskSpaceWarningEventArgs)
      RaiseEvent DiskSpaceWarning(me, e)
   End Sub
End Class
using System;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;

public class DiskSpaceWarningEventArgs : EventArgs
{
   private long currentFreeSpace;
   private long currentTotalSpace;
   private string driveName;

   public DiskSpaceWarningEventArgs(string name, long freeSpace, long totalSpace)
   {
      this.driveName = name;
      this.currentFreeSpace = freeSpace;
      this.currentTotalSpace = totalSpace;
   }

   public string Name
   {
      get { return this.driveName; }
   }

   public long FreeSpace
   {
      get { return this.currentFreeSpace; }
   }

   public long TotalSpace
   {
      get { return this.currentTotalSpace; }
   }
}

public delegate void DiskSpaceWarningEventHandler(object sender, 
                                                  DiskSpaceWarningEventArgs e);

public class DiskSpaceMonitor
{
   public event DiskSpaceWarningEventHandler DiskSpaceWarning;
   private decimal threshhold;

   public DiskSpaceMonitor()
   {
      // Retrieve threshhold to fire event from configuration file.
      try
      {
         NameValueCollection settings = ConfigurationManager.AppSettings;
         this.threshhold = Convert.ToDecimal(settings["Threshhold"]);
      }
      // If there is no configuration file, provide a default value.
      catch (ConfigurationErrorsException)
      {
         this.threshhold = 10m;
      }
      catch (InvalidCastException)
      {
         this.threshhold = 10m;
      }
   }

   public void CheckFreeSpace()
   {
      // Get drives present on system.
      DriveInfo[] drives = DriveInfo.GetDrives();
      foreach (DriveInfo drive in drives)
      {
         if (drive.IsReady)
         {
            if (drive.TotalFreeSpace/drive.TotalSize <= this.threshhold)
               OnDiskSpaceWarning(new DiskSpaceWarningEventArgs(drive.Name, 
                                  drive.TotalFreeSpace, drive.TotalSize));
         }
      }
   }

   protected void OnDiskSpaceWarning(DiskSpaceWarningEventArgs e)
   {
      if (DiskSpaceWarning != null)
         DiskSpaceWarning(this, e);
   }   
}

Zamiast korzystać z EventArgs klasy do dostarczania danych zdarzenia, przykład definiuje klasę danych zdarzenia niestandardowego o nazwie DiskSpaceWarningEventArgs. Zapewnia obsługę zdarzeń nazwę dysku, jak również ilości wolnego i całkowitego miejsca na dysku. Przykład definiuje również delegata, DiskSpaceWarningEventHandler, która reprezentuje podpisu zdarzenia.

DiskSpaceMonitor w klasie DiskSpaceWarning zdarzenia i zapewnia także OnDiskSpaceWarning metodę, która wywołuje zdarzenie. OnDiskSpaceWarning z kolei wywołaniu metody CheckFreeSpace metoda po wykryciu wolnego miejsca na dysku jest mniejsza niż wartość procentową, która jest zdefiniowana w pliku konfiguracyjnym.

Zobacz też

Zadania

Jak: podnoszenie i zużywają zdarzeń

Koncepcje

Zdarzenia i pełnomocnicy

Podnoszenie zdarzenie

Inne zasoby

Obsługa i podnoszenie zdarzeń