How to remove all event handlers from an event

后端 未结 18 1906
再見小時候
再見小時候 2020-11-22 01:20

To create a new event handler on a control you can do this

c.Click += new EventHandler(mainFormButton_Click);

or this

c.Cli         


        
18条回答
  •  庸人自扰
    2020-11-22 01:44

    I hated any complete solutions shown here, I did a mix and tested now, worked for any event handler:

    public class MyMain()
        public void MyMethod() {
            AnotherClass.TheEventHandler += DoSomeThing;
        }
    
        private void DoSomething(object sender, EventArgs e) {
            Debug.WriteLine("I did something");
            AnotherClass.ClearAllDelegatesOfTheEventHandler();
        }
    
    }
    
    public static class AnotherClass {
    
        public static event EventHandler TheEventHandler;
    
        public static void ClearAllDelegatesOfTheEventHandler() {
    
            foreach (Delegate d in TheEventHandler.GetInvocationList())
            {
                TheEventHandler -= (EventHandler)d;
            }
        }
    }
    

    Easy! Thanks for Stephen Punak.

    I used it because I use a generic local method to remove the delegates and the local method was called after different cases, when different delegates are setted.

提交回复
热议问题