tags:

views:

37

answers:

2

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

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

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

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

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

This will raise error "...The event 'EventA' can only appear on the left hand side of += or -= ...". I don't know how to make it.

I figure out of a way to enumerate all handlers in EventA but don't know how to. Please help.

+1  A: 

An event is a bit similar to properties: In properties you have a backing field and get/set accessors. With automatic properties, you have no access to the backing field.

Similarly, events have a backing field and an add/remove accessor. If you don't specify anything, it is automatically created. You could try by creating a backing field in your class A and use thiat data in class B. See example 2 of http://msdn.microsoft.com/en-us/library/8627sbea(VS.71).aspx for such a backing field.

Daniel Rose
+4  A: 

You can have access to the InvocationList of an event but only from inside the class.

So your solution could look like:

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 ain't pretty.

Henk Holterman
Thanks! It's done now.I have a question: Why can we only have access to the InvocationList of an event from inside the class?
Nam Gi VU
@Nam: By design. Events are (like) properties and the InvocationList is private.
Henk Holterman