(E-Mail Removed) wrote:
> 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
--
http://barrkel.blogspot.com/