EventHandler<TEventArgs> Delegado
Definición
Representa el método que controlará un evento si el evento proporciona datos.Represents the method that will handle an event when the event provides data.
generic <typename TEventArgs>
public delegate void EventHandler(System::Object ^ sender, TEventArgs e);
generic <typename TEventArgs>
where TEventArgs : EventArgspublic delegate void EventHandler(System::Object ^ sender, TEventArgs e);
public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);
public delegate void EventHandler<TEventArgs>(object? sender, TEventArgs e);
[System.Serializable]
public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e) where TEventArgs : EventArgs;
[System.Serializable]
public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);
type EventHandler<'EventArgs> = delegate of obj * 'EventArgs -> unit
[<System.Serializable>]
type EventHandler<'EventArgs (requires 'EventArgs :> EventArgs)> = delegate of obj * 'EventArgs -> unit
[<System.Serializable>]
type EventHandler<'EventArgs> = delegate of obj * 'EventArgs -> unit
Public Delegate Sub EventHandler(Of TEventArgs)(sender As Object, e As TEventArgs)
Parámetros de tipo
- TEventArgs
Tipo de datos de evento generados por el evento.The type of the event data generated by the event.
Parámetros
- sender
- Object
Origen del evento.The source of the event.
- e
- TEventArgs
Objeto que contiene los datos del evento.An object that contains the event data.
- Herencia
- Atributos
Ejemplos
En el ejemplo siguiente se muestra un evento denominado ThresholdReached
.The following example shows an event named ThresholdReached
. El evento está asociado a un EventHandler<TEventArgs> delegado.The event is associated with an EventHandler<TEventArgs> delegate.
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 ConsoleApplication1
{
class Program
{
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
Comentarios
El modelo de eventos del .NET Framework se basa en tener un delegado de eventos que conecta un evento con su controlador.The event model in the .NET Framework is based on having an event delegate that connects an event with its handler. Para generar un evento, se necesitan dos elementos:To raise an event, two elements are needed:
Delegado que hace referencia a un método que proporciona la respuesta al evento.A delegate that refers to a method that provides the response to the event.
Opcionalmente, una clase que contiene los datos del evento, si el evento proporciona datos.Optionally, a class that holds the event data, if the event provides data.
El delegado es un tipo que define una firma, es decir, el tipo de valor devuelto y los tipos de lista de parámetros de un método.The delegate is a type that defines a signature, that is, the return value type and parameter list types for a method. Puede usar el tipo de delegado para declarar una variable que pueda hacer referencia a cualquier método con la misma firma que el delegado.You can use the delegate type to declare a variable that can refer to any method with the same signature as the delegate.
La firma estándar de un delegado de controlador de eventos define un método que no devuelve ningún valor.The standard signature of an event handler delegate defines a method that does not return a value. El primer parámetro de este método es de tipo Object y hace referencia a la instancia que genera el evento.This method's first parameter is of type Object and refers to the instance that raises the event. Su segundo parámetro se deriva del tipo EventArgs y contiene los datos del evento.Its second parameter is derived from type EventArgs and holds the event data. Si el evento no genera datos de evento, el segundo parámetro es simplemente el valor del EventArgs.Empty campo.If the event does not generate event data, the second parameter is simply the value of the EventArgs.Empty field. De lo contrario, el segundo parámetro es un tipo derivado de EventArgs y proporciona los campos o propiedades necesarios para contener los datos de evento.Otherwise, the second parameter is a type derived from EventArgs and supplies any fields or properties needed to hold the event data.
El EventHandler<TEventArgs> delegado es un delegado predefinido que representa un método de control de eventos para un evento que genera datos.The EventHandler<TEventArgs> delegate is a predefined delegate that represents an event handler method for an event that generates data. La ventaja de utilizar EventHandler<TEventArgs> es que no es necesario codificar su propio delegado personalizado si el evento genera datos de evento.The advantage of using EventHandler<TEventArgs> is that you do not need to code your own custom delegate if your event generates event data. Basta con proporcionar el tipo del objeto de datos de evento como parámetro genérico.You simply provide the type of the event data object as the generic parameter.
Para asociar el evento al método que controlará el evento, agregue una instancia del delegado al evento.To associate the event with the method that will handle the event, add an instance of the delegate to the event. Siempre que se produce el evento, se llama a su controlador, a menos que se quite el delegado.The event handler is called whenever the event occurs, unless you remove the delegate.
Para obtener más información sobre los delegados de controladores de eventos, vea controlar y provocar eventos.For more information about event handler delegates, see Handling and Raising Events.
Métodos de extensión
GetMethodInfo(Delegate) |
Obtiene un objeto que representa el método representado por el delegado especificado.Gets an object that represents the method represented by the specified delegate. |
Se aplica a
Consulte también
- EventHandler
- EventArgs
- Delegate
- Controlar y provocar eventosHandling and Raising Events
- Procedimiento para provocar y consumir eventosHow to: Raise and Consume Events
- Eventos (Visual Basic)Events (Visual Basic)
- Eventos (Guía de programación de C#)Events (C# Programming Guide)
- Introducción a eventos y eventos enrutados (aplicaciones de la Tienda Windows)Events and routed events overview (Windows store apps)