C# event handling (compared to Java)

后端 未结 9 701
离开以前
离开以前 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:21

    In c# events are delegates. They behave in a similar way to a function pointer in C/C++ but are actual classes derived from System.Delegate.

    In this case, create a custom EventArgs class to pass the Computer object.

    public class ComputerEventArgs : EventArgs
    {
      private Computer _computer;
    
      public ComputerEventArgs(Computer computer) {
        _computer = computer;
      }
    
      public Computer Computer { get { return _computer; } }
    }
    

    Then expose the events from the producer:

    public class ComputerEventProducer
    {
      public event EventHandler Started;
      public event EventHandler Stopped;
      public event EventHandler Reset;
      public event EventHandler Error;
    
      /*
      // Invokes the Started event */
      private void OnStarted(Computer computer) {
        if( Started != null ) {
          Started(this, new ComputerEventArgs(computer));
        }
      }
    
      // Add OnStopped, OnReset and OnError
    
    }
    

    The consumer of the events then binds a handler function to each event on the consumer.

    public class ComputerEventConsumer
    {
      public void ComputerEventConsumer(ComputerEventProducer producer) {
        producer.Started += new EventHandler(ComputerStarted);
        // Add other event handlers
      }
    
      private void ComputerStarted(object sender, ComputerEventArgs e) {
      }
    }
    

    When the ComputerEventProducer calls OnStarted the Started event is invoked which in turn will call the ComputerEventConsumer.ComputerStarted method.

提交回复
热议问题