How to add all handlers (delegates) of an event instance to another event instance of the same event type?

I have two classes A and B. In class A, I have an EventA event

public delegate void FolderStructureChangedHandler(); public event FolderStructureChangedHandler EventA; 

In class B, I have the same event called EventB. In the method of my application, I want to add all the handlers registered in EventA to the EventB event

 A classA = new classA(); classA.EventA += delegate1(); classA.EventA += delegate2(); B classB = new classB(); classB.EventB += classA.EventA; 

This will cause the error "... EventA event can appear only on the left side + = or - = ...". I do not know how to do that.

I figure out a way to list all the handlers in EventA, but I don’t know how to do it. Please, help.

+4
source share
2 answers

You can access the InvocationList event, but only from within the class.

So your solution might look like this:

 class A { public event FolderStructureChangedHandler EventA; public void CopyHandlers(B b) { var handlers = EventA.GetInvocationList(); foreach (var h in handlers) { b.EventB += (EventHandler) h; } } } 

But it is ugly.

+4
source

The event is a bit like properties: In properties you have a support field and get / set accessors. With automatic properties, you do not have access to the backup field.

Similarly, events have a support field and an auxiliary add / remove element. If you do not specify anything, it will be automatically created. You can try to create a support field in your class A and use the thiat data in class B. See Example 2 http://msdn.microsoft.com/en-us/library/8627sbea(VS.71).aspx for such a support field .

+2
source

All Articles