Jak zrobić własne wydarzenie w C#?

Jak zrobić własne wydarzenie w C#?

 103
Author: wonea, 2009-03-08

4 answers

Oto przykład tworzenia i używania zdarzenia w 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();
        }
    }
}
 186
Author: Gary Willoughby,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-20 13:41:10

Mam pełną dyskusję na temat wydarzeń i delegatów w moim artykule Wydarzenia . W przypadku najprostszych zdarzeń można po prostu zadeklarować Zdarzenie publiczne, a kompilator utworzy zarówno Zdarzenie, jak i pole do śledzenia subskrybentów:

public event EventHandler Foo;

Jeśli potrzebujesz bardziej skomplikowanej logiki subskrypcji/wypisania, możesz to zrobić jawnie:

public event EventHandler Foo
{
    add
    {
        // Subscription logic here
    }
    remove
    {
        // Unsubscription logic here
    }
}
 51
Author: Jon Skeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-21 17:11:37

Możesz zadeklarować Zdarzenie za pomocą następującego kodu:

public event EventHandler MyOwnEvent;

W razie potrzeby można użyć niestandardowego typu delegata zamiast Eventhandlera.

Szczegółowe informacje/tutoriale dotyczące korzystania z wydarzeń W. NET znajdziesz w artykule samouczek wydarzeń (MSDN).

 20
Author: Brann,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-12 13:05:51

Aby to zrobić musimy znać trzy składniki

  1. miejsce odpowiedzialne za firing the Event
  2. miejsce odpowiedzialne za responding to the Event
  3. Samo wydarzenie

    A. Zdarzenie

    B .EventArgs

    C. EventArgs wyliczenie

Teraz pozwala utworzyć zdarzenie, które zostanie wywołane, gdy funkcja zostanie wywołana

Ale mój rozkaz rozwiązania tego problemu w ten sposób: używam klasy, zanim ją stworzę

  1. The miejsce odpowiedzialne za 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 jest klasą statyczną, wyjaśnię to później

Następnym krokiem jest

  1. Miejsce odpowiedzialne za 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));
    

Trzeci krok

  1. samo wydarzenie

Wypaczałem Zdarzenie w klasie o nazwie 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
}

Ta klasa zawiera terazthe Event, EventArgs i EventArgs Enums i the function odpowiedzialne za wywołanie zdarzenia

Przepraszam za tak długi odpowiedź

 3
Author: Basheer AL-MOMANI,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-26 06:54:08