How do I unsubscribe all handlers from an event for a particular class in C#?

后端 未结 5 1597
滥情空心
滥情空心 2020-12-08 07:04

Basic premise:

I have a Room which publishes an event when an Avatar \"enters\" to all Avatars within the Room. When an Avatar leaves the Room I want it to remove a

5条回答
  •  遥遥无期
    2020-12-08 07:36

    Each delegate has a method named GetInvocationList() that returns all the actual delegates that have been registered. So, assuming the delegate Type (or event) is named say MyDelegate, and the handler instance variable is named myDlgHandler, you can write:

    Delegate[] clientList = myDlgHandler.GetInvocationList();
    foreach (var d in clientList)
           myDlgHandler -= (d as MyDelegate);
    

    to cover the case where it might be null,

     if(myDlgHandler != null)
      foreach (var d in myDlgHandler.GetInvocationList())
           myDlgHandler -= (d as MyDelegate);
    

提交回复
热议问题