Connecting to events via Reflection

D

dmcdougald

I posted a month or so ago and never got a response. So I'm trying
again.

I just moved over to C#2. In 1.1 I implemented a generic event
handler strategy by emitting a handler of the correct signature type.
However, with Covariance/Contravariance in C#2 I hoped to clean
things
up.

Since this works in 2.0:

button1.Click += GenericEventHandler; // Just a normal EventHandler
button1.MouseDown += GenericEventHandler; // a MouseEventHandler


private void GenericEventHandler(object sender, EventArgs args)
{
}


I had hoped to be able to do something similar to the above code via
Reflection. So I tried this:

eventInfo.AddEventHandler(instance, new
EventHandler(GenericEventHandler);

But if the eventInfo.EventHandlerType is not a basic EventHandler I
receive the following error:

Object of type 'System.EventHandler' cannot be converted to type
'System.Windows.Forms.MouseEventHandler'.

Is there any way to make this happen?

Thanks
 
B

Barry Kelly

I just moved over to C#2. In 1.1 I implemented a generic event
handler strategy by emitting a handler of the correct signature type.
However, with Covariance/Contravariance in C#2 I hoped to clean
things
up.

Since this works in 2.0:

button1.Click += GenericEventHandler; // Just a normal EventHandler
button1.MouseDown += GenericEventHandler; // a MouseEventHandler

private void GenericEventHandler(object sender, EventArgs args)

You've got the location of the variance wrong in your mental model. The
variance is located at the point of binding the method to the delegate,
not the point of attaching the delegate to the event.

The above code is equivalent to:

button1.MouseDown += new MouseEventHandler(GenericEventHandler);
I had hoped to be able to do something similar to the above code via
Reflection. So I tried this:

eventInfo.AddEventHandler(instance, new
EventHandler(GenericEventHandler);

So, you need to create a MouseEventHandler rather than an EventHandler,
but GenericEventHandler should fit into MouseEventHandler's constructor.

You can use Delegate.CreateDelegate to make it more general, of course,
and possibly EventInfo to discover the correct delegate type.

-- Barry
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top