Need to connect to events generically via Reflection

D

dmcdougald

Hi,

I just moved over to C#2. In 1.1 I implemented a generic event
handler stragey 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:

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

Bruce Wood

Hi,

I just moved over to C#2. In 1.1 I implemented a generic event
handler stragey 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:

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

private void GenericEventHandler(object sender, EventArgs args)
{

}

I don't understand how this could have worked in 1.1, given that
GenericEventHandler is the name of a method, and the += operator
expects a delegate...?
 
D

dmcdougald

I don't understand how this could have worked in 1.1, given that
GenericEventHandler is the name of a method, and the += operator
expects a delegate...?- Hide quoted text -

- Show quoted text -

It did not work in 1.1. But we just moved to 2.0. I was just using
that as an example of what can be done in code in 2.0. I want to do
the same thing via Reflection in 2.0.
 

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