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 이며 이벤트를 발생시키는 instance 참조합니다. 두 번째 매개 변수는 형식 EventArgs 에서 파생되고 이벤트 데이터를 보유합니다. 이벤트가 이벤트 데이터를 생성하지 않는 경우 두 번째 매개 변수는 단순히 필드 값입니다 EventArgs.Empty . 그렇지 않으면 두 번째 매개 변수는 에서 EventArgs 파생된 형식이며 이벤트 데이터를 보유하는 데 필요한 필드 또는 속성을 제공합니다.

EventHandler<TEventArgs> 대리자는 데이터를 생성하는 이벤트에 대한 이벤트 처리기 메서드를 나타내는 미리 정의된 대리자입니다. 를 사용하면 EventHandler<TEventArgs> 이벤트가 이벤트 데이터를 생성하는 경우 사용자 지정 대리자를 직접 코딩할 필요가 없다는 장점이 있습니다. 이벤트 데이터 개체의 형식을 제네릭 매개 변수로 제공하기만 하면 됩니다.

이벤트를 처리할 메서드와 이벤트를 연결하려면 대리자의 instance 이벤트에 추가합니다. 대리자를 제거하지 않는 경우 이벤트가 발생할 때마다 이벤트 처리기가 호출됩니다.

이벤트 처리기 대리자에 대 한 자세한 내용은 참조 하세요. 이벤트 처리 및 발생합니다.

확장 메서드

GetMethodInfo(Delegate)

지정된 대리자가 나타내는 메서드를 나타내는 개체를 가져옵니다.

적용 대상

추가 정보