EventHandler<TEventArgs> 代理人

定義

代表事件提供資料時處理事件的方法。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)

類型參數

TEventArgs

此事件所產生的事件資料型別。The type of the event data generated by the event.

參數

sender
Object

事件的來源。The source of the event.

e

包含事件資料的物件。An object that contains the event data.

繼承
EventHandler<TEventArgs>
屬性

範例

下列範例會顯示名為ThresholdReached的事件。The following example shows an event named ThresholdReached. 事件與EventHandler<TEventArgs>委派相關聯。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

備註

.NET Framework 中的事件模型是以具有將事件與其處理常式連接的事件委派為基礎。The event model in the .NET Framework is based on having an event delegate that connects an event with its handler. 若要引發事件, 需要兩個元素:To raise an event, two elements are needed:

  • 委派, 它會參考提供事件回應的方法。A delegate that refers to a method that provides the response to the event.

  • (選擇性) 包含事件資料的類別 (如果事件提供資料)。Optionally, a class that holds the event data, if the event provides data.

委派是一種定義簽章的類型, 也就是方法的傳回數值型別和參數清單類型。The delegate is a type that defines a signature, that is, the return value type and parameter list types for a method. 您可以使用委派類型來宣告變數, 其可參考具有與委派相同簽章的任何方法。You can use the delegate type to declare a variable that can refer to any method with the same signature as the delegate.

事件處理常式委派的標準簽章會定義不會傳回值的方法。The standard signature of an event handler delegate defines a method that does not return a value. 這個方法的第一個參數是型Object別, 而則是指引發事件的實例。This method's first parameter is of type Object and refers to the instance that raises the event. 其第二個參數衍生自EventArgs類型, 並保留事件資料。Its second parameter is derived from type EventArgs and holds the event data. 如果事件不會產生事件資料, 第二個參數就只是EventArgs.Empty欄位的值。If the event does not generate event data, the second parameter is simply the value of the EventArgs.Empty field. 否則, 第二個參數是衍生自EventArgs的類型, 並提供保存事件資料所需的任何欄位或屬性。Otherwise, the second parameter is a type derived from EventArgs and supplies any fields or properties needed to hold the event data.

EventHandler<TEventArgs>委派是預先定義的委派, 表示產生資料之事件的事件處理常式方法。The EventHandler<TEventArgs> delegate is a predefined delegate that represents an event handler method for an event that generates data. 使用EventHandler<TEventArgs>的優點是, 如果您的事件會產生事件資料, 您就不需要撰寫自己的自訂委派程式碼。The advantage of using EventHandler<TEventArgs> is that you do not need to code your own custom delegate if your event generates event data. 您只需提供事件資料物件的類型做為泛型參數即可。You simply provide the type of the event data object as the generic parameter.

若要將事件與將處理事件的方法產生關聯, 請將委派的實例加入至事件。To associate the event with the method that will handle the event, add an instance of the delegate to the event. 除非您移除委派,否則每當事件發生時就會呼叫事件處理常式。The event handler is called whenever the event occurs, unless you remove the delegate.

如需事件處理常式委派的詳細資訊, 請參閱處理和引發事件For more information about event handler delegates, see Handling and Raising Events.

擴充方法

GetMethodInfo(Delegate)

取得表示特定委派所代表之方法的物件。Gets an object that represents the method represented by the specified delegate.

適用於

另請參閱