Come posso creare il mio evento in C #?


122

Come posso creare il mio evento in C #?

Risposte:


217

Ecco un esempio di creazione e utilizzo di un evento con C #

using System;

namespace Event_Example
{
    //First we have to define a delegate that acts as a signature for the
    //function that is ultimately called when the event is triggered.
    //You will notice that the second parameter is of MyEventArgs type.
    //This object will contain information about the triggered event.
    public delegate void MyEventHandler(object source, MyEventArgs e);

    //This is a class which describes the event to the class that recieves it.
    //An EventArgs class must always derive from System.EventArgs.
    public class MyEventArgs : EventArgs
    {
        private string EventInfo;
        public MyEventArgs(string Text)
        {
            EventInfo = Text;
        }
        public string GetInfo()
        {
            return EventInfo;
        }
    }

    //This next class is the one which contains an event and triggers it
    //once an action is performed. For example, lets trigger this event
    //once a variable is incremented over a particular value. Notice the
    //event uses the MyEventHandler delegate to create a signature
    //for the called function.
    public class MyClass
    {
        public event MyEventHandler OnMaximum;
        private int i;
        private int Maximum = 10;
        public int MyValue
        {
            get
            {
                return i;
            }
            set
            {
                if(value <= Maximum)
                {
                    i = value;
                }
                else
                {
                    //To make sure we only trigger the event if a handler is present
                    //we check the event to make sure it's not null.
                    if(OnMaximum != null)
                    {
                        OnMaximum(this, new MyEventArgs("You've entered " +
                            value.ToString() +
                            ", but the maximum is " +
                            Maximum.ToString()));
                    }
                }
            }
        }
    }

    class Program
    {
        //This is the actual method that will be assigned to the event handler
        //within the above class. This is where we perform an action once the
        //event has been triggered.
        static void MaximumReached(object source, MyEventArgs e)
        {
            Console.WriteLine(e.GetInfo());
        }

        static void Main(string[] args)
        {
            //Now lets test the event contained in the above class.
            MyClass MyObject = new MyClass();
            MyObject.OnMaximum += new MyEventHandler(MaximumReached);

            for(int x = 0; x <= 15; x++)
            {
                MyObject.MyValue = x;
            }

            Console.ReadLine();
        }
    }
}

4
Dopo aver visitato un centinaio di spiegazioni, questo mi ha finalmente aiutato a capire. SE aveva ragione, i post sono ancora rilevanti dopo diversi anni.

1
{Meh!} Mi dimentico sempre di scrivere nella eventparte per la classe.
jp2code

51

Ho una discussione completa di eventi e delegati nel mio articolo sugli eventi . Per il tipo più semplice di evento, puoi semplicemente dichiarare un evento pubblico e il compilatore creerà sia un evento che un campo per tenere traccia degli iscritti:

public event EventHandler Foo;

Se hai bisogno di una logica di sottoscrizione / annullamento più complicata, puoi farlo esplicitamente:

public event EventHandler Foo
{
    add
    {
        // Subscription logic here
    }
    remove
    {
        // Unsubscription logic here
    }
}

1
Non ero sicuro di come chiamare l'evento dal mio codice, ma risulta essere davvero ovvio. Basta chiamarlo come un metodo passandogli un mittente e un oggetto EventArgs. [es. if (fooHappened) Foo (sender, eventArgs); ]
Richard Garside,

2
@Richard: Non proprio; è necessario gestire il caso in cui non sono presenti sottoscrittori, quindi il riferimento al delegato sarà nullo.
Jon Skeet,

In attesa dell'aggiornamento C # 4 sugli eventi thread-safe nell'articolo che hai collegato. Davvero un ottimo lavoro, @JonSkeet!
kdbanman

20

Puoi dichiarare un evento con il codice seguente:

public event EventHandler MyOwnEvent;

Se necessario, è possibile utilizzare un tipo di delegato personalizzato anziché EventHandler.

Puoi trovare informazioni dettagliate / tutorial sull'uso degli eventi in .NET nell'articolo Events Tutorial (MSDN).


4

per farlo dobbiamo conoscere i tre componenti

  1. il luogo responsabile firing the Event
  2. il luogo responsabile responding to the Event
  3. l'evento stesso

    un. Evento

    b .EventArgs

    c. Enumerazione EventArgs

ora creiamo un evento che viene attivato quando viene chiamata una funzione

ma ho il mio ordine di risolvere questo problema in questo modo: sto usando la classe prima di crearla

  1. il luogo responsabile responding to the Event

    NetLog.OnMessageFired += delegate(object o, MessageEventArgs args) 
    {
            // when the Event Happened I want to Update the UI
            // this is WPF Window (WPF Project)  
            this.Dispatcher.Invoke(() =>
            {
                LabelFileName.Content = args.ItemUri;
                LabelOperation.Content = args.Operation;
                LabelStatus.Content = args.Status;
            });
    };
    

NetLog è una classe statica che spiegherò in seguito

il passo successivo è

  1. il luogo responsabile firing the Event

    //this is the sender object, MessageEventArgs Is a class I want to create it  and Operation and Status are Event enums
    NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Started));
    downloadFile = service.DownloadFile(item.Uri);
    NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Finished));
    

la terza fase

  1. l'evento stesso

Ho deformato l'evento all'interno di una classe chiamata NetLog

public sealed class NetLog
{
    public delegate void MessageEventHandler(object sender, MessageEventArgs args);

    public static event MessageEventHandler OnMessageFired;
    public static void FireMessage(Object obj,MessageEventArgs eventArgs)
    {
        if (OnMessageFired != null)
        {
            OnMessageFired(obj, eventArgs);
        }
    }
}

public class MessageEventArgs : EventArgs
{
    public string ItemUri { get; private set; }
    public Operation Operation { get; private set; }
    public Status Status { get; private set; }

    public MessageEventArgs(string itemUri, Operation operation, Status status)
    {
        ItemUri = itemUri;
        Operation = operation;
        Status = status;
    }
}

public enum Operation
{
    Upload,Download
}

public enum Status
{
    Started,Finished
}

questa classe contiene ora the Event, EventArgse EventArgs Enumse the functionresponsabile per generare l'evento

scusa per questa lunga risposta


La differenza fondamentale in questa risposta è rendere statico l'evento, che consente di ricevere eventi senza richiedere un riferimento all'oggetto che ha generato l'evento. Ottimo per iscriversi a eventi da più controlli indipendenti.
Radderz
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.