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

Definice

Představuje metodu, která zpracuje událost v případě, že událost poskytuje data.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)

Parametry typu

TEventArgs

Typ dat události generovaných událostí.The type of the event data generated by the event.

Parametry

sender
Object Object Object Object

Zdroj událostiThe source of the event.

e

Objekt, který obsahuje data události.An object that contains the event data.

Dědičnost
EventHandler<TEventArgs>EventHandler<TEventArgs>EventHandler<TEventArgs>EventHandler<TEventArgs>
Atributy

Příklady

Následující příklad ukazuje událost s názvem ThresholdReached.The following example shows an event named ThresholdReached. Událost je přidružena EventHandler<TEventArgs> k delegátovi.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

Poznámky

Model události v .NET Framework je založen na tom, že má delegáta události, který propojuje událost s obslužnou rutinou.The event model in the .NET Framework is based on having an event delegate that connects an event with its handler. Pro vyvolání události jsou vyžadovány dva prvky:To raise an event, two elements are needed:

  • Delegát, který odkazuje na metodu, která poskytuje odpověď na událost.A delegate that refers to a method that provides the response to the event.

  • Volitelně třídu, která obsahuje data události, pokud událost poskytuje data.Optionally, a class that holds the event data, if the event provides data.

Delegát je typ, který definuje signaturu, to znamená typ návratové hodnoty a typy seznamů parametrů pro metodu.The delegate is a type that defines a signature, that is, the return value type and parameter list types for a method. Můžete použít typ delegáta k deklaraci proměnné, která může odkazovat na jakoukoli metodu se stejnou signaturou jako delegát.You can use the delegate type to declare a variable that can refer to any method with the same signature as the delegate.

Standardní podpis delegáta obslužné rutiny události definuje metodu, která nevrací hodnotu.The standard signature of an event handler delegate defines a method that does not return a value. První parametr metody je typu Object a odkazuje na instanci, která vyvolává událost.This method's first parameter is of type Object and refers to the instance that raises the event. Jeho druhý parametr je odvozen z typu EventArgs a obsahuje data události.Its second parameter is derived from type EventArgs and holds the event data. Pokud událost negeneruje data události, druhý parametr je jednoduše hodnotou EventArgs.Empty pole.If the event does not generate event data, the second parameter is simply the value of the EventArgs.Empty field. V opačném případě je druhý parametr typ odvozený EventArgs z a poskytuje všechna pole nebo vlastnosti potřebné k uchování dat události.Otherwise, the second parameter is a type derived from EventArgs and supplies any fields or properties needed to hold the event data.

EventHandler<TEventArgs> Delegát je předdefinovaný delegát, který představuje metodu obslužné rutiny události pro událost, která generuje data.The EventHandler<TEventArgs> delegate is a predefined delegate that represents an event handler method for an event that generates data. Výhodou použití EventHandler<TEventArgs> je, že nemusíte kódovat vlastní delegát, pokud událost generuje data události.The advantage of using EventHandler<TEventArgs> is that you do not need to code your own custom delegate if your event generates event data. Jednoduše zadejte typ datového objektu události jako obecný parametr.You simply provide the type of the event data object as the generic parameter.

Chcete-li přidružit událost k metodě, která zpracuje událost, přidejte do události instanci delegáta.To associate the event with the method that will handle the event, add an instance of the delegate to the event. Obslužná rutina události je volána při každém výskytu události, dokud neodeberete delegáta.The event handler is called whenever the event occurs, unless you remove the delegate.

Další informace o delegátech obslužných rutin událostí naleznete v tématu manipulace a vyvolávání událostí.For more information about event handler delegates, see Handling and Raising Events.

Metody rozšíření

GetMethodInfo(Delegate) GetMethodInfo(Delegate) GetMethodInfo(Delegate) GetMethodInfo(Delegate)

Získává objekt, který představuje metodu reprezentovanou zadaným delegátem.Gets an object that represents the method represented by the specified delegate.

Platí pro

Viz také