C removes all event binding methods

  • 2021-01-19 22:20:59
  • OfStack

This article illustrates C#'s method of removing all event bindings. Share with you for your reference. The specific analysis is as follows:


private delegate int DEL_TEST_EventHandler(int m, int n);
private event DEL_TEST_EventHandler DelTestEventHandler;
/// <summary>
///  Remove all event bindings 
/// </summary>
/// <param name="clearEvent"></param>
private void clear_event(DEL_TEST_EventHandler clearEvent)
{
 Delegate[] dels = DelTestEventHandler.GetInvocationList();
 foreach (Delegate d in dels)
 {
  // Get the method name 
  object delObj = d.GetType().GetProperty("Method").GetValue(d, null);
  string funcName = (string)delObj.GetType().GetProperty("Name").GetValue(delObj, null);
    Debug.Print(funcName);
  DelTestEventHandler -= d as DEL_TEST_EventHandler;
 }
}
// Test main function 
private void test()
{
 DelTestEventHandler += add;
 DelTestEventHandler += sub;
   DelTestEventHandler += add;
 DelTestEventHandler += sub;
   clear_event(DelTestEventHandler);
}
private int add(int m, int n)
{
 return m + n;
}
private static int sub(int m, int n)
{
 return m - n;
}

I hope this article is helpful to your C# program design.


Related articles: