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

后端 未结 5 1604
滥情空心
滥情空心 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:22

    Is there anything wrong with a standard remove?

    public void RemovePlayer(Avatar theAvatar) {
     AvatarEntersRoom -= new EventHandler(theAvatar.HandleAvatarEntersRoom);
    
    }
    

    EDIT

    Based on your update it appears that you want code that will remove a particular object from all events on a particular class. There is no realistic way to accomplish this goal. It's often a bit verbose but the best way is to individually add/remove a particular object method combo from every event.

    The only way to get close to this functionality is to use reflection. You could reflectively grab all events on your class and then do some magic to find all instances of a class within the event chain. This will only be a partial solution though because it will ignore such things as a lambda expression event handlers.

提交回复
热议问题