EventHandler 委托

定义

表示将用于处理不具有事件数据的事件的方法。

public delegate void EventHandler(System::Object ^ sender, EventArgs ^ e);
public delegate void EventHandler(object sender, EventArgs e);
public delegate void EventHandler(object? sender, EventArgs e);
[System.Serializable]
public delegate void EventHandler(object sender, EventArgs e);
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public delegate void EventHandler(object sender, EventArgs e);
type EventHandler = delegate of obj * EventArgs -> unit
[<System.Serializable>]
type EventHandler = delegate of obj * EventArgs -> unit
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type EventHandler = delegate of obj * EventArgs -> unit
Public Delegate Sub EventHandler(sender As Object, e As EventArgs)

参数

sender
Object

事件源。

e
EventArgs

不包含事件数据的对象。

属性

示例

以下示例演示与委托关联的EventHandler名为 ThresholdReached 的事件。 分配给委托的方法 EventHandler 在 方法中 OnThresholdReached 调用。

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 ConsoleApplication3
{
    public class Program3
    {
        public static void Main()
        {
            Counter c = new(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 readonly int _threshold;
        private int _total;

        public Counter(int passedThreshold)
        {
            _threshold = passedThreshold;
        }

        public void Add(int x)
        {
            _total += x;
            if (_total >= _threshold)
            {
                ThresholdReachedEventArgs args = new()
                {
                    Threshold = _threshold,
                    TimeReached = DateTime.Now
                };
                OnThresholdReached(args);
            }
        }

        protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
        {
            ThresholdReached?.Invoke(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 是预定义的委托,专门表示不生成数据的事件的事件处理程序方法。 如果事件确实生成了数据,则必须使用泛型 EventHandler<TEventArgs> 委托类。

若要将事件与将处理事件的方法相关联,请将 委托的实例添加到 事件。 除非移除了该委托,否则每当发生该事件时就会调用事件处理程序。

有关事件处理程序委托的详细信息,请参阅 处理和引发事件

扩展方法

GetMethodInfo(Delegate)

获取指示指定委托表示的方法的对象。

适用于

另请参阅