C# event handling (compared to Java)

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

    Ok, FINAL clarification!: So this is pretty much the best I can do code-wise to implement those events?

       public class Computer {
    
            public event EventHandler Started;
    
            public event EventHandler Stopped;
    
            public event EventHandler Reset;
    
            public event EventHandler BreakPointHit;
    
            public event EventHandler Error;
    
            public Computer() {
                Started = delegate { };
                Stopped = delegate { };
                Reset = delegate { };
                BreakPointHit = delegate { };
                Error = delegate { };
            }
    
            protected void OnStarted() {
                Started(this, EventArgs.Empty);
            }
    
            protected void OnStopped() {
                Stopped(this, EventArgs.Empty);
            }
    
            protected void OnReset() {
                Reset(this, EventArgs.Empty);
            }
    
            protected void OnBreakPointHit(int breakPoint) {
                BreakPointHit(this, new BreakPointEvent(breakPoint));
            }
    
            protected void OnError(System.Exception exception) {
                Error(this, new ExceptionEvent(exception));
            }
        }
    }
    

提交回复
热议问题