Understanding events and event handlers in C#

后端 未结 12 1506
野性不改
野性不改 2020-11-22 04:06

I understand the purpose of events, especially within the context of creating user interfaces. I think this is the prototype for creating an event:

public vo         


        
相关标签:
12条回答
  • 2020-11-22 04:28

    Here is a code example which may help:

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    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 receives 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();
        }
      }
    }
    
    0 讨论(0)
  • 2020-11-22 04:29

    I agree with KE50 except that I view the 'event' keyword as an alias for 'ActionCollection' since the event holds a collection of actions to be performed (ie. the delegate).

    using System;
    
    namespace test{
    
    class MyTestApp{
        //The Event Handler declaration
        public delegate void EventAction();
    
        //The Event Action Collection 
        //Equivalent to 
        //  public List<EventAction> EventActions=new List<EventAction>();
        //        
        public event EventAction EventActions;
    
        //An Action
        public void Hello(){
            Console.WriteLine("Hello World of events!");
        }
        //Another Action
        public void Goodbye(){
            Console.WriteLine("Goodbye Cruel World of events!");
        }
    
        public static void Main(){
            MyTestApp TestApp = new MyTestApp();
    
            //Add actions to the collection
            TestApp.EventActions += TestApp.Hello;
            TestApp.EventActions += TestApp.Goodbye;
    
            //Invoke all event actions
            if (TestApp.EventActions!= null){
                //this peculiar syntax hides the invoke 
                TestApp.EventActions();
                //using the 'ActionCollection' idea:
                // foreach(EventAction action in TestApp.EventActions)
                //     action.Invoke();
            }
        }
    
    }   
    
    }
    
    0 讨论(0)
  • 2020-11-22 04:31

    I recently made an example of how to use events in c#, and posted it on my blog. I tried to make it as clear as possible, with a very simple example. In case it might help anyone, here it is: http://www.konsfik.com/using-events-in-csharp/

    It includes description and source code (with lots of comments), and it mainly focuses on a proper (template - like) usage of events and event handlers.

    Some key points are:

    • Events are like "sub - types of delegates", only more constrained (in a good way). In fact an event's declaration always includes a delegate (EventHandlers are a type of delegate).

    • Event Handlers are specific types of delegates (you may think of them as a template), which force the user to create events which have a specific "signature". The signature is of the format: (object sender, EventArgs eventarguments).

    • You may create your own sub-class of EventArgs, in order to include any type of information the event needs to convey. It is not necessary to use EventHandlers when using events. You may completely skip them and use your own kind of delegate in their place.

    • One key difference between using events and delegates, is that events can only be invoked from within the class that they were declared in, even though they may be declared as public. This is a very important distinction, because it allows your events to be exposed so that they are "connected" to external methods, while at the same time they are protected from "external misuse".

    0 讨论(0)
  • 2020-11-22 04:36

    Another thing to know about, in some cases, you have to use the Delegates/Events when you need a low level of coupling !

    If you want to use a component in several place in application, you need to make a component with low level of coupling and the specific unconcerned LOGIC must be delegated OUTSIDE of your component ! This ensures that you have a decoupled system and a cleaner code.

    In SOLID principle this is the "D", (Dependency inversion principle).

    Also known as "IoC", Inversion of control.

    You can make "IoC" with Events, Delegates and DI (Dependency Injection).

    It's easy to access a method in a child class. But more difficult to access a method in a parent class from child. You have to pass the parent reference to the child ! (or use DI with Interface)

    Delegates/Events allows us to communicate from the child to the parent without reference !

    In this diagram above, I do not use Delegate/Event and the parent component B has to have a reference of the parent component A to execute the unconcerned business logic in method of A. (high level of coupling)

    With this approach, I would have to put all the references of all components that use component B ! :(

    In this diagram above, I use Delegate/Event and the component B doesn't have to known A. (low level of coupling)

    And you can use your component B anywhere in your application !

    0 讨论(0)
  • 2020-11-22 04:41

    That is actually the declaration for an event handler - a method that will get called when an event is fired. To create an event, you'd write something like this:

    public class Foo
    {
        public event EventHandler MyEvent;
    }
    

    And then you can subscribe to the event like this:

    Foo foo = new Foo();
    foo.MyEvent += new EventHandler(this.OnMyEvent);
    

    With OnMyEvent() defined like this:

    private void OnMyEvent(object sender, EventArgs e)
    {
        MessageBox.Show("MyEvent fired!");
    }
    

    Whenever Foo fires off MyEvent, then your OnMyEvent handler will be called.

    You don't always have to use an instance of EventArgs as the second parameter. If you want to include additional information, you can use a class derived from EventArgs (EventArgs is the base by convention). For example, if you look at some of the events defined on Control in WinForms, or FrameworkElement in WPF, you can see examples of events that pass additional information to the event handlers.

    0 讨论(0)
  • 2020-11-22 04:41

    publisher: where the events happen. Publisher should specify which delegate the class is using and generate necessary arguments, pass those arguments and itself to the delegate.

    subscriber: where the response happen. Subscriber should specify methods to respond to events. These methods should take the same type of arguments as the delegate. Subscriber then add this method to publisher's delegate.

    Therefore, when the event happen in publisher, delegate will receive some event arguments (data, etc), but publisher has no idea what will happen with all these data. Subscribers can create methods in their own class to respond to events in publisher's class, so that subscribers can respond to publisher's events.

    0 讨论(0)
提交回复
热议问题