Bagikan melalui


EventHandler Delegasikan

Definisi

Mewakili metode yang akan menangani peristiwa yang tidak memiliki data peristiwa.

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)

Parameter

sender
Object

Sumber dari peristiwa tersebut.

e
EventArgs

Objek yang tidak berisi data peristiwa.

Atribut

Contoh

Contoh berikut menunjukkan peristiwa bernama ThresholdReached yang terkait dengan EventHandler delegasi. Metode yang EventHandler ditetapkan ke delegasi dipanggil dalam OnThresholdReached metode .

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

Keterangan

Model peristiwa di .NET Framework didasarkan pada memiliki delegasi peristiwa yang menghubungkan peristiwa dengan handler-nya. Untuk menaikkan peristiwa, diperlukan dua elemen:

  • Delegasi yang mengidentifikasi metode yang memberikan respons terhadap peristiwa tersebut.

  • Secara opsional, kelas yang menyimpan data peristiwa, jika peristiwa menyediakan data.

Delegasi adalah jenis yang menentukan tanda tangan, yaitu jenis nilai yang dikembalikan dan jenis daftar parameter untuk metode. Anda dapat menggunakan jenis delegasi untuk mendeklarasikan variabel yang dapat merujuk ke metode apa pun dengan tanda tangan yang sama dengan delegasi.

Tanda tangan standar delegasi penanganan aktivitas menentukan metode yang tidak mengembalikan nilai. Parameter pertama metode ini berjenis Object dan mengacu pada instans yang meningkatkan peristiwa. Parameter kedua berasal dari jenis EventArgs dan menyimpan data peristiwa. Jika peristiwa tidak menghasilkan data peristiwa, parameter kedua hanyalah nilai EventArgs.Empty bidang . Jika tidak, parameter kedua adalah jenis yang berasal dari EventArgs dan memasok bidang atau properti apa pun yang diperlukan untuk menyimpan data peristiwa.

Delegasi EventHandler adalah delegasi yang telah ditentukan sebelumnya yang secara khusus mewakili metode penanganan aktivitas untuk peristiwa yang tidak menghasilkan data. Jika peristiwa Anda menghasilkan data, Anda harus menggunakan kelas delegasi generik EventHandler<TEventArgs> .

Untuk mengaitkan peristiwa dengan metode yang akan menangani peristiwa, tambahkan instans delegasi ke peristiwa. Penanganan aktivitas dipanggil setiap kali peristiwa terjadi, kecuali Anda menghapus delegasi.

Untuk informasi selengkapnya tentang delegasi penanganan aktivitas, lihat Menangani dan Menaikkan Peristiwa.

Metode Ekstensi

GetMethodInfo(Delegate)

Mendapatkan objek yang mewakili metode yang diwakili oleh delegasi yang ditentukan.

Berlaku untuk

Lihat juga