C# event handling (compared to Java)

后端 未结 9 706
离开以前
离开以前 2020-12-23 23:23

I am currently having a hardtime understanding and implementing events in C# using delagates. I am used to the Java way of doing things:

  1. Define an interface f
9条回答
  •  臣服心动
    2020-12-24 00:12

    First of all, there is a standard method signature in .Net that is typically used for events. The languages allow any sort of method signature at all to be used for events, and there are some experts who believe the convention is flawed (I mostly agree), but it is what it is and I will follow it for this example.

    1. Create a class that will contain the event’s parameters (derived from EventArgs).
    public class ComputerEventArgs : EventArgs 
    {
      Computer computer; 
      // constructor, properties, etc.
    }
    
    1. Create a public event on the class that is to fire the event.
        class ComputerEventGenerator  // I picked a terrible name BTW.
        {
          public event EventHandler ComputerStarted;
          public event EventHandler ComputerStopped;
          public event EventHandler ComputerReset;
        ...
        }
    
    1. Call the events.
        class ComputerEventGenerator
        {
        ...
          private void OnComputerStarted(Computer computer) 
          {
            EventHandler temp = ComputerStarted;
            if (temp != null) temp(this, new ComputerEventArgs(computer)); // replace "this" with null if the event is static
          }
         }
    
    1. Attach a handler for the event.
        void OnLoad()
        {
          ComputerEventGenerator computerEventGenerator = new ComputerEventGenerator();
          computerEventGenerator.ComputerStarted += new  EventHandler(ComputerEventGenerator_ComputerStarted);
        }
    
    1. Create the handler you just attached (mostly by pressing the Tab key in VS).
        private void ComputerEventGenerator_ComputerStarted(object sender, ComputerEventArgs args)
        {
          if (args.Computer.Name == "HAL9000")
             ShutItDownNow(args.Computer);
        }
    
    1. Don't forget to detach the handler when you're done. (Forgetting to do this is the biggest source of memory leaks in C#!)
        void OnClose()
        {
          ComputerEventGenerator.ComputerStarted -= ComputerEventGenerator_ComputerStarted;
        }
    

    And that's it!

    EDIT: I honestly can't figure out why my numbered points all appear as "1." I hate computers.

提交回复
热议问题