EventHandler<TEventArgs> EventHandler<TEventArgs> EventHandler<TEventArgs> EventHandler<TEventArgs> Delegate

Definición

Representa el método que controlará eventos cuando el evento proporcione 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);
[System.Serializable]
public delegate void EventHandler<TEventArgs>(object sender, TEventArgs e);
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 los datos de evento generados por el evento.The type of the event data generated by the event.

Parámetros

sender
Object Object Object Object

Origen del evento.The source of the event.

e

Objeto que contiene los datos del evento.An object that contains the event data.

Herencia
EventHandler<TEventArgs>EventHandler<TEventArgs>EventHandler<TEventArgs>EventHandler<TEventArgs>
Atributos

Ejemplos

El ejemplo siguiente muestra un evento denominado ThresholdReached.The following example shows an event named ThresholdReached. El evento está asociado con un EventHandler<TEventArgs> delegar.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 de .NET Framework se basa en tener un delegado del evento que se conecta a 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:

  • Un 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 para 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 puede 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 un valor.The standard signature of an event handler delegate defines a method that does not return a value. 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. Se deriva su segundo parámetro de 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 eventos, el segundo parámetro es simplemente el valor de la EventArgs.Empty campo.If the event does not generate event data, the second parameter is simply the value of the EventArgs.Empty field. En caso contrario, el segundo parámetro es un tipo derivado de EventArgs y proporciona los campos o propiedades necesarias para albergar los datos del 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 controlador de eventos para un evento que genera los datos.The EventHandler<TEventArgs> delegate is a predefined delegate that represents an event handler method for an event that generates data. La ventaja de usar EventHandler<TEventArgs> es que no es necesario codificar su propio delegado personalizado si el evento genera datos de eventos.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 del evento como el parámetro genérico.You simply provide the type of the event data object as the generic parameter.

Para asociar el evento con el 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 controlador de eventos, consulte controlar y provocar eventos.For more information about event handler delegates, see Handling and Raising Events.

Métodos de extensión

GetMethodInfo(Delegate) GetMethodInfo(Delegate) GetMethodInfo(Delegate) 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: