EventHandler<TEventArgs> Delegat

Definicja

Reprezentuje metodę, która będzie obsługiwać zdarzenie, gdy zdarzenie zawiera dane.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)

Parametry typu

TEventArgs

Typ danych zdarzenia wygenerowanych przez zdarzenie.The type of the event data generated by the event.

Parametry

sender
Object

Źródło zdarzenia.The source of the event.

e
TEventArgs

Obiekt, który zawiera dane zdarzenia.An object that contains the event data.

Dziedziczenie
EventHandler<TEventArgs>
Atrybuty

Przykłady

Poniższy przykład pokazuje zdarzenie o nazwie ThresholdReached .The following example shows an event named ThresholdReached. Zdarzenie jest skojarzone z EventHandler<TEventArgs> delegatem.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

Uwagi

Model zdarzenia w .NET Framework opiera się na utworzeniu delegata zdarzenia, który łączy zdarzenie z obsługą.The event model in the .NET Framework is based on having an event delegate that connects an event with its handler. Aby zgłosić zdarzenie, są konieczne dwa elementy:To raise an event, two elements are needed:

  • Delegat odwołujący się do metody, która dostarcza odpowiedź na zdarzenie.A delegate that refers to a method that provides the response to the event.

  • Opcjonalnie, Klasa, która przechowuje dane zdarzenia, jeśli zdarzenie zawiera dane.Optionally, a class that holds the event data, if the event provides data.

Delegat jest typem, który definiuje sygnaturę, czyli typ wartości zwracanej i typy list parametrów dla metody.The delegate is a type that defines a signature, that is, the return value type and parameter list types for a method. Możesz użyć typu delegata, aby zadeklarować zmienną, która może odwoływać się do dowolnej metody o tej samej sygnaturze, co delegat.You can use the delegate type to declare a variable that can refer to any method with the same signature as the delegate.

Standardowy podpis delegata programu obsługi zdarzeń definiuje metodę, która nie zwraca wartości.The standard signature of an event handler delegate defines a method that does not return a value. Pierwszy parametr metody jest typu Object i odwołuje się do wystąpienia, które wywołuje zdarzenie.This method's first parameter is of type Object and refers to the instance that raises the event. Drugi parametr pochodzi od typu EventArgs i przechowuje dane zdarzenia.Its second parameter is derived from type EventArgs and holds the event data. Jeśli zdarzenie nie generuje danych zdarzenia, drugi parametr jest po prostu wartością EventArgs.Empty pola.If the event does not generate event data, the second parameter is simply the value of the EventArgs.Empty field. W przeciwnym razie drugi parametr jest typem pochodnym EventArgs i dostarcza wszystkie pola lub właściwości potrzebne do przechowywania danych zdarzenia.Otherwise, the second parameter is a type derived from EventArgs and supplies any fields or properties needed to hold the event data.

EventHandler<TEventArgs>Delegat jest wstępnie zdefiniowanym delegatem, który reprezentuje metodę obsługi zdarzeń dla zdarzenia, które generuje dane.The EventHandler<TEventArgs> delegate is a predefined delegate that represents an event handler method for an event that generates data. Zaletą korzystania z programu EventHandler<TEventArgs> jest to, że nie trzeba kodu własnego delegata niestandardowego, jeśli zdarzenie generuje dane zdarzenia.The advantage of using EventHandler<TEventArgs> is that you do not need to code your own custom delegate if your event generates event data. Wystarczy podać typ obiektu danych zdarzenia jako parametr generyczny.You simply provide the type of the event data object as the generic parameter.

Aby skojarzyć zdarzenie z metodą, która będzie obsługiwać zdarzenie, Dodaj wystąpienie delegata do zdarzenia.To associate the event with the method that will handle the event, add an instance of the delegate to the event. Program obsługi zdarzeń jest wywoływany przy każdym wystąpieniu zdarzenia, o ile nie usunięto delegata.The event handler is called whenever the event occurs, unless you remove the delegate.

Aby uzyskać więcej informacji na temat delegatów obsługi zdarzeń, zobacz temat Obsługa iwywoływanie zdarzeń.For more information about event handler delegates, see Handling and Raising Events.

Metody rozszerzania

GetMethodInfo(Delegate)

Pobiera obiekt, który reprezentuje metodę reprezentowaną przez określony delegat.Gets an object that represents the method represented by the specified delegate.

Dotyczy

Zobacz też