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 all subscriptions for that room.
How can I best unsubscribe the Avatar from all events in the room before I add the Avatar to a new Room and subscribe to the new Room’s events?
The code goes something like this:
class Room { public event EventHandler<EnterRoomEventArgs> AvatarEntersRoom; public event EvnetHandler<LeaveRoomEventArgs> AvatarLeavesRoom; public event EventHandler<AnotherOfManyEventArgs> AnotherOfManayAvatarEvents; public void AddPlayer(Avatar theAvatar) { AvatarEntersRoom(this, new EnterRoomEventArgs()); AvatarEntersRoom += new EventHandler<EnterRoomEventArgs>(theAvatar.HandleAvatarEntersRoom); AvatarLeavesRoom += new EventHandler<EnterRoomEventArgs>(theAvatar.HandleAvatarEntersRoom); AnotherOfManayAvatarEvents += new EventHandler<EnterRoomEventArgs>(theAvatar.HandleAvatarEntersRoom); } } class Avatar { public void HandleAvatarEntersRoom(object sender, EnterRoomEventArgs e) { Log.Write('avatar has entered the room'); } public void HandleAvatarLeaveRoom(object sender, LeaveRoomEventArgs e) { Log.Write('avatar has left room'); } public void HandleAnotherOfManayAvatarEvents(object sender, AnotherOfManyEventArgs e) { Log.Write('another avatar event has occurred'); } }
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 sayMyDelegate, and the handler instance variable is namedmyDlgHandler, you can write:to cover the case where it might be null,