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

前端 未结 4 775
傲寒
傲寒 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.

    0 讨论(0)
  • 2020-11-29 07:39

    With an explicit event, you need to provide your own backing store - either a delegate field or something like EventHandlerList. The current code is recursive. Try:

    private EventHandler itemsProcessed;
    public event EventHandler ItemsProcessed
    {
        add
        {
            itemsProcessed-= value;
            itemsProcessed+= value;
        }
    
        remove
        {
            itemsProcessed-= value;
        }
    }
    

    Then (and noting I'm being a little cautious about the "about to turn null" edge-case re threading):

    var snapshot = itemsProcessed;
    if(snapshot != null) snapshot(this, EventArgs.Empty);
    

    With more recent C# versions, this can be simplified:

    itemsProcessed?.Invoke(this, EventArgs.Empty);
    
    0 讨论(0)
  • 2020-11-29 07:41

    It seems that if you implement the EventHandler explicitly, you can't refer to the 'Property' when firing the event. You must refer to the backing store.

    0 讨论(0)
  • 2020-11-29 07:42

    What error? I guess its stack overflow error, because you are calling add and remove on yourserlf (same event). Also you cannot raise event ACCESSOR.

    Valid way to do this is to create backing private event, that will be added and removed to from public accessor, and you should raise this private event.

    Dang, minute late.

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