EventHandler<TEventArgs> Делегат

Определение

Представляет метод, обрабатывающий событие, когда событие предоставляет данные.

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)

Параметры типа

TEventArgs

Тип данных события, создаваемых событием.

Параметры

sender
Object

Источник события.

e
TEventArgs

Объект, содержащий данные о событии.

Атрибуты

Примеры

В следующем примере показано событие с именем ThresholdReached. Событие связано с делегатом EventHandler<TEventArgs> .

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; }
    }
}
open System

type ThresholdReachedEventArgs(threshold, timeReached) =
    inherit EventArgs()
    member _.Threshold = threshold
    member _.TimeReached = timeReached

type Counter(threshold) =
    let mutable total = 0

    let thresholdReached = Event<_>()

    member this.Add(x) =
        total <- total + x
        if total >= threshold then
            let args = ThresholdReachedEventArgs(threshold, DateTime.Now)
            thresholdReached.Trigger(this, args)

    [<CLIEvent>]
    member _.ThresholdReached = thresholdReached.Publish

let c_ThresholdReached(sender, e: ThresholdReachedEventArgs) =
    printfn $"The threshold of {e.Threshold} was reached at {e.TimeReached}."
    exit 0

let c = Counter(Random().Next 10)
c.ThresholdReached.Add c_ThresholdReached

printfn "press 'a' key to increase total"
while Console.ReadKey(true).KeyChar = 'a' do
    printfn "adding one"
    c.Add 1
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

Комментарии

Модель событий в платформа .NET Framework основана на наличии делегата события, который соединяет событие с его обработчиком. Чтобы вызвать событие, требуются два элемента:

  • Делегат, ссылающийся на метод, предоставляющий ответ на событие.

  • При необходимости класс, содержащий данные события, если событие предоставляет данные.

Делегат — это тип, определяющий сигнатуру, то есть тип возвращаемого значения и типы списка параметров для метода. Тип делегата можно использовать для объявления переменной, которая может ссылаться на любой метод с той же сигнатурой, что и делегат.

Стандартная сигнатура делегата обработчика событий определяет метод, который не возвращает значение. Первый параметр этого метода имеет тип Object и ссылается на экземпляр, который вызывает событие . Второй параметр является производным от типа EventArgs и содержит данные события. Если событие не создает данные события, вторым параметром является просто значение EventArgs.Empty поля. В противном случае второй параметр является типом, производным от EventArgs , и предоставляет все поля или свойства, необходимые для хранения данных события.

Делегат EventHandler<TEventArgs> — это предопределенный делегат, представляющий метод обработчика событий для события, создающего данные. Преимущество использования EventHandler<TEventArgs> заключается в том, что вам не нужно кодировать собственный пользовательский делегат, если событие создает данные события. Просто укажите тип объекта данных события в качестве универсального параметра.

Чтобы связать событие с методом, который будет обрабатывать событие, добавьте экземпляр делегата в событие . Обработчик событий вызывается всякий раз, когда происходит событие, если делегат не удален.

Дополнительные сведения о делегатах обработчика событий см. в разделе Обработка и вызов событий.

Методы расширения

GetMethodInfo(Delegate)

Получает объект, представляющий метод, представленный указанным делегатом.

Применяется к

См. также раздел