-event- can only appear on the left hand side of += or -=

前端 未结 4 1081
傲寒
傲寒 2020-11-29 07:22

I have an event in a loop. I am trying to prevent the same method being added to an event more than once. I\'ve implemented the add and remove acce

4条回答
  •  鱼传尺愫
    2020-11-29 07:35

    I can't tell from your post if you are trying to raise the event from a derived class or not, but one thing I've found is that you can't define an event in a base class and then raise it (directly) in a derived class, for some reason that isn't real clear to me yet.

    So I define protected functions in base classes to raise events (that are defined in those base classes), like this:

    // The signature for a handler of the ProgressStarted event.
    // title: The title/label for a progress dialog/bar.
    // total: The max progress value.
    public delegate void ProgressStartedType(string title, int total);
    
    // Raised when progress on a potentially long running process is started.
    public event ProgressStartedType ProgressStarted;
    
    // Used from derived classes to raise ProgressStarted.
    protected void RaiseProgressStarted(string title, int total) {
        if (ProgressStarted != null) ProgressStarted(title, total);
    }
    

    Then in the derived class, I call RaiseProgressStarted(title, total) instead of calling ProgressStarted(title, total).

    It seems like kind of the long way around. Maybe someone else knows of a better way around this problem.

提交回复
热议问题