Postupy: Vyvolávání a zpracovávání událostí
Příklady v tomto článku ukazují, jak pracovat s událostmi. Zahrnují příklady delegáta EventHandler , delegáta EventHandler<TEventArgs> a vlastního delegáta pro ilustraci událostí s daty a bez nich.
Příklady používají koncepty popsané v článku Události .
Příklad 1
První příklad ukazuje, jak vyvolat a využívat událost, která neobsahuje data. Obsahuje třídu s názvem Counter
, která má událost s názvem ThresholdReached
. Tato událost se vyvolá, když se hodnota čítače rovná nebo překročí prahovou hodnotu. Delegát EventHandler je přidružený k události, protože nejsou k dispozici žádná data události.
using System;
namespace ConsoleApplication1
{
class ProgramOne
{
static void Main(string[] args)
{
Counter c = new Counter(new Random().Next(10));
c.ThresholdReached += c_ThresholdReached;
Console.WriteLine("press 'a' key to increase total");
while (Console.ReadKey(true).KeyChar == 'a')
{
Console.WriteLine("adding one");
c.Add(1);
}
}
static void c_ThresholdReached(object sender, EventArgs e)
{
Console.WriteLine("The threshold was reached.");
Environment.Exit(0);
}
}
class Counter
{
private int threshold;
private int total;
public Counter(int passedThreshold)
{
threshold = passedThreshold;
}
public void Add(int x)
{
total += x;
if (total >= threshold)
{
ThresholdReached?.Invoke(this, EventArgs.Empty);
}
}
public event EventHandler ThresholdReached;
}
}
Module Module1
Sub Main()
Dim c As Counter = New Counter(New Random().Next(10))
AddHandler c.ThresholdReached, AddressOf c_ThresholdReached
Console.WriteLine("press 'a' key to increase total")
While Console.ReadKey(True).KeyChar = "a"
Console.WriteLine("adding one")
c.Add(1)
End While
End Sub
Sub c_ThresholdReached(sender As Object, e As EventArgs)
Console.WriteLine("The threshold was reached.")
Environment.Exit(0)
End Sub
End Module
Class Counter
Private threshold As Integer
Private total As Integer
Public Sub New(passedThreshold As Integer)
threshold = passedThreshold
End Sub
Public Sub Add(x As Integer)
total = total + x
If (total >= threshold) Then
ThresholdReached?.Invoke(this. EventArgs.Empty)
End If
End Sub
Public Event ThresholdReached As EventHandler
End Class
Příklad 2
Druhý příklad ukazuje, jak vyvolat a využívat událost, která poskytuje data. Delegát EventHandler<TEventArgs> je přidružen k události a je k dispozici instance vlastního datového objektu události.
using namespace System;
public ref class ThresholdReachedEventArgs : public EventArgs
{
public:
property int Threshold;
property DateTime TimeReached;
};
public ref class Counter
{
private:
int threshold;
int total;
public:
Counter() {};
Counter(int passedThreshold)
{
threshold = passedThreshold;
}
void Add(int x)
{
total += x;
if (total >= threshold) {
ThresholdReachedEventArgs^ args = gcnew ThresholdReachedEventArgs();
args->Threshold = threshold;
args->TimeReached = DateTime::Now;
OnThresholdReached(args);
}
}
event EventHandler<ThresholdReachedEventArgs^>^ ThresholdReached;
protected:
virtual void OnThresholdReached(ThresholdReachedEventArgs^ e)
{
ThresholdReached(this, e);
}
};
public ref class SampleHandler
{
public:
static void c_ThresholdReached(Object^ sender, ThresholdReachedEventArgs^ e)
{
Console::WriteLine("The threshold of {0} was reached at {1}.",
e->Threshold, e->TimeReached);
Environment::Exit(0);
}
};
void main()
{
Counter^ c = gcnew Counter((gcnew Random())->Next(10));
c->ThresholdReached += gcnew EventHandler<ThresholdReachedEventArgs^>(SampleHandler::c_ThresholdReached);
Console::WriteLine("press 'a' key to increase total");
while (Console::ReadKey(true).KeyChar == 'a') {
Console::WriteLine("adding one");
c->Add(1);
}
}
using System;
namespace ConsoleApplication3
{
class ProgramThree
{
static void Main(string[] args)
{
Counter c = new Counter(new Random().Next(10));
c.ThresholdReached += c_ThresholdReached;
Console.WriteLine("press 'a' key to increase total");
while (Console.ReadKey(true).KeyChar == 'a')
{
Console.WriteLine("adding one");
c.Add(1);
}
}
static void c_ThresholdReached(object sender, ThresholdReachedEventArgs e)
{
Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached);
Environment.Exit(0);
}
}
class Counter
{
private int threshold;
private int total;
public Counter(int passedThreshold)
{
threshold = passedThreshold;
}
public void Add(int x)
{
total += x;
if (total >= threshold)
{
ThresholdReachedEventArgs args = new ThresholdReachedEventArgs();
args.Threshold = threshold;
args.TimeReached = DateTime.Now;
OnThresholdReached(args);
}
}
protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
{
EventHandler<ThresholdReachedEventArgs> handler = ThresholdReached;
if (handler != null)
{
handler(this, e);
}
}
public event EventHandler<ThresholdReachedEventArgs> ThresholdReached;
}
public class ThresholdReachedEventArgs : EventArgs
{
public int Threshold { get; set; }
public DateTime TimeReached { get; set; }
}
}
Module Module1
Sub Main()
Dim c As Counter = New Counter(New Random().Next(10))
AddHandler c.ThresholdReached, AddressOf c_ThresholdReached
Console.WriteLine("press 'a' key to increase total")
While Console.ReadKey(True).KeyChar = "a"
Console.WriteLine("adding one")
c.Add(1)
End While
End Sub
Sub c_ThresholdReached(sender As Object, e As ThresholdReachedEventArgs)
Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached)
Environment.Exit(0)
End Sub
End Module
Class Counter
Private threshold As Integer
Private total As Integer
Public Sub New(passedThreshold As Integer)
threshold = passedThreshold
End Sub
Public Sub Add(x As Integer)
total = total + x
If (total >= threshold) Then
Dim args As ThresholdReachedEventArgs = New ThresholdReachedEventArgs()
args.Threshold = threshold
args.TimeReached = DateTime.Now
OnThresholdReached(args)
End If
End Sub
Protected Overridable Sub OnThresholdReached(e As ThresholdReachedEventArgs)
RaiseEvent ThresholdReached(Me, e)
End Sub
Public Event ThresholdReached As EventHandler(Of ThresholdReachedEventArgs)
End Class
Class ThresholdReachedEventArgs
Inherits EventArgs
Public Property Threshold As Integer
Public Property TimeReached As DateTime
End Class
Příklad 3
Třetí příklad ukazuje, jak deklarovat delegáta pro událost. Delegát má název ThresholdReachedEventHandler
. Tento příklad je jen ilustrace. Obvykle nemusíte deklarovat delegáta pro událost, protože můžete použít buď delegáta EventHandler , nebo delegáta EventHandler<TEventArgs> . Delegáta byste měli deklarovat pouze ve výjimečných scénářích, jako je zpřístupnění třídy pro starší verze kódu, který nemůže používat obecné typy.
using System;
namespace ConsoleApplication4
{
class ProgramFour
{
static void Main(string[] args)
{
Counter c = new Counter(new Random().Next(10));
c.ThresholdReached += c_ThresholdReached;
Console.WriteLine("press 'a' key to increase total");
while (Console.ReadKey(true).KeyChar == 'a')
{
Console.WriteLine("adding one");
c.Add(1);
}
}
static void c_ThresholdReached(Object sender, ThresholdReachedEventArgs e)
{
Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached);
Environment.Exit(0);
}
}
class Counter
{
private int threshold;
private int total;
public Counter(int passedThreshold)
{
threshold = passedThreshold;
}
public void Add(int x)
{
total += x;
if (total >= threshold)
{
ThresholdReachedEventArgs args = new ThresholdReachedEventArgs();
args.Threshold = threshold;
args.TimeReached = DateTime.Now;
OnThresholdReached(args);
}
}
protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
{
ThresholdReachedEventHandler handler = ThresholdReached;
if (handler != null)
{
handler(this, e);
}
}
public event ThresholdReachedEventHandler ThresholdReached;
}
public class ThresholdReachedEventArgs : EventArgs
{
public int Threshold { get; set; }
public DateTime TimeReached { get; set; }
}
public delegate void ThresholdReachedEventHandler(Object sender, ThresholdReachedEventArgs e);
}
Module Module1
Sub Main()
Dim c As Counter = New Counter(New Random().Next(10))
AddHandler c.ThresholdReached, AddressOf c_ThresholdReached
Console.WriteLine("press 'a' key to increase total")
While Console.ReadKey(True).KeyChar = "a"
Console.WriteLine("adding one")
c.Add(1)
End While
End Sub
Sub c_ThresholdReached(sender As Object, e As ThresholdReachedEventArgs)
Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached)
Environment.Exit(0)
End Sub
End Module
Class Counter
Private threshold As Integer
Private total As Integer
Public Sub New(passedThreshold As Integer)
threshold = passedThreshold
End Sub
Public Sub Add(x As Integer)
total = total + x
If (total >= threshold) Then
Dim args As ThresholdReachedEventArgs = New ThresholdReachedEventArgs()
args.Threshold = threshold
args.TimeReached = DateTime.Now
OnThresholdReached(args)
End If
End Sub
Protected Overridable Sub OnThresholdReached(e As ThresholdReachedEventArgs)
RaiseEvent ThresholdReached(Me, e)
End Sub
Public Event ThresholdReached As ThresholdReachedEventHandler
End Class
Public Class ThresholdReachedEventArgs
Inherits EventArgs
Public Property Threshold As Integer
Public Property TimeReached As DateTime
End Class
Public Delegate Sub ThresholdReachedEventHandler(sender As Object, e As ThresholdReachedEventArgs)