How to determine if an event is already subscribed

前端 未结 7 1679
傲寒
傲寒 2020-11-29 02:08

In my .NET application I am subscribing to events from another class. The subscription is conditional. I am subscribing to events when the control is visible and de-subscrib

相关标签:
7条回答
  • 2020-11-29 03:05

    Can you put the decision making logic into the method that fires the event? Assuming you're using Winforms it'd look something like this:

     if (MyEvent != null && isCriteriaFulfilled)
    {
        MyEvent();
    }
    

    Where isCriteriaFulfilled is determined by your visible/invisible logic.

    // UPDATES /////

    Further to your 1st comment would it not make sense to alter the behaviour inside your event handler depending on the value of this.Visible?

     a.Delegate += new Delegate(method1);
    ...
    private void method1()
    {
        if (this.Visible)
            // Do Stuff
    }
    

    Or if you really have to go with subscribing and unsubscribing:

     private Delegate _method1 = null;
    ...
    if(this.visible) 
    {
        if (_method1 == null)
            _method1 = new Delegate(method1);
        a.Delegate += _method1;
    }
    else if (_method1 != null)
    {
        a.Delegate -= _method1;
    } 
    
    0 讨论(0)
提交回复
热议问题