كيفية القيام بما يلي: تنفيذ الأحداث في الفئة الخاصة بك
تصف الإجراءات التالية كيفية تنفيذ حدث في فئة. الإجراء الأول ينفذ حدث ليس لديه بيانات مقترنة; يستخدم الفئات System.EventArgs و System.EventHandler لبيانات الحدث و معالج المفوض. الإجراء الثاني ينفذ حدث مع بيانات مخصصة;يعرف فئات مخصصة لبيانات الحدث و معالج مفوض الحدث.
![]() |
---|
يوضح هذا الموضوع كيفية تعريف و رفع حدث في فئة.إنه لا يوضح كيفية تعريف معالج حدث يستهلك ذلك الحدث.للمعلومات حول كيفية إستهلاك الأحداث, راجع استهلاك الأحداث و كيفية القيام بما يلي: إطلاق و استهلاك الأحداث. |
للحصول على مثال كامل يوضح تنفيذ و معالجة الأحداث, راجع كيفية القيام بما يلي: إطلاق و استهلاك الأحداث .
لتنفيذ حدث بدون بيانات الحدث الخاصة
عرف عضو حدث عام في الفئة الخاصة بك. عيّن نُوع عضو الحدث إلى المفوض System.EventHandler.
Public Class Countdown ' ... Public Event CountdownCompleted As EventHandler End Class
public class Countdown { // ... public event EventHandler CountdownCompleted; }
وفر أسلوب محمي في الفئة الخاصة بك يرفع الحدث. سمي الأسلوب OnEventName. إرفع الحدث داخل الإسلوب. لاحظ أن تعليمات C# البرمجية يجب أن تتحقق لتحدد ما إذا كان الحدث فارغاً قبل رفع الحدث. هذا يلغي الحاجة لمعالجة الـ NullReferenceException الذي يتم طرحه عند رفع حدث و لكن لم يتم إرفاق معالجات أحداث به. هذا الاختبار ضروري في هذه الحالة بسبب أن الفئة CountDown ترفع الحدث ببساطة ولكن لا توفر معالج له.
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); } }
حدد متى ترفع الحدث في الفئة الخاصة بك. إستدعي OnEventName لرفع الحدث.
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()); } }
لتنفيذ حدث مع بيانات الحدث الخاصة
عرف فئة توفر البيانات للحدث. سمي الفئة EventNameArgs ، إشتق الفئة من System.EventArgs ، و أضف أي أعضاء خاصة بالحدث.
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; } } }
عرف مفوض للحدث. سمي المفوض EventNameEventHandler.
Public Delegate Sub AlarmEventHandler(sender As Object, e As AlarmEventArgs)
public delegate void AlarmEventHandler(object sender, AlarmEventArgs e);
عرف عضو حدث عام يُسَمى EventName في الفئة الخاصة بك. عيّن نُوع عضو الحدث إلى نوع مفوض الحدث.
Public Class AlarmClock ' ... Public Event Alarm As AlarmEventHandler End Class
public class AlarmClock { // ... public event AlarmEventHandler Alarm; }
عرف أسلوب محمي في الفئة الخاصة بك يرفع الحدث. سمي الأسلوب OnEventName. إرفع الحدث داخل الإسلوب. لاحظ أن تعليمات C# البرمجية يجب أن تتحقق لتحدد ما إذا كان الحدث فارغاً قبل رفع الحدث. هذا يلغي الحاجة لمعالجة الـ NullReferenceException الذي يتم طرحه عند رفع حدث و لكن لم يتم إرفاق معالجات أحداث به. هذا الاختبار ضروري في هذه الحالة بسبب أن الفئة CountDown ترفع الحدث ببساطة ولكن لا توفر معالج له.
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); } }
حدد متى ترفع الحدث في الفئة الخاصة بك. إستدعي OnEventName لرفع الحدث و لتمرير البيانات الخاصة بالحدث باستخدام 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); } }
مثال
يعرف المثال التالي فئة DiskSpaceMonitor التي تستخدم حدث لإنتاج تحذير عندما تنخفض مساحة القرص الفارغة أقل من النسبة المئوية المعرفة في ملف التكوين. كما يُعرّف أيضاً فئة DiskSpaceWarningEventArgs لتوفير بيانات مخصصة على مساحة القرص الفارغة إلى معالجات الحدث.
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);
}
}
بدلاً من استخدام الفئة EventArgs لتوفير بيانات الحدث ، المثال يعرف فئة بيانات حدث مخصصة مسماة DiskSpaceWarningEventArgs. إنها توفر لمعالجات الأحداث اسم محرك الأقراص بالإضافة إلى مقدار المساحة الفارغة و إجمالي المساحة المتوفرة على محرك الأقراص. يعرف المثال أيضاً مفوض , DiskSpaceWarningEventHandler ، الذي يمثل توقيع الحدث.
الفئة DiskSpaceMonitor تعرف الحدث DiskSpaceWarning كما توفر أسلوب OnDiskSpaceWarning الذي يرفع الحدث. الأسلوب OnDiskSpaceWarning بدوره يتم استدعاءه من قِبَل الأسلوب CheckFreeSpace عندما يكتشف أن المساحة الفارغة المتوفرة على محرك أقراص أقل من أو تساوي النسبة المئوية المعرفة في ملف التكوين.
راجع أيضًا:
المهام
كيفية القيام بما يلي: إطلاق و استهلاك الأحداث