I came across a situation where I needed to deal with Delegate internally, but I needed a general constraint. In particular, I wanted to add an event handler using reflection, but I wanted to use a common argument for the delegate. The code below does NOT work, since the "Handler" is a type variable, and the compiler will not distinguish Handler until Delegate :
public void AddHandler<Handler>(Control c, string eventName, Handler d) { c.GetType().GetEvent(eventName).AddEventHandler(c, (Delegate) d); }
However, you can pass a function that performs the conversion for you. convert takes a Handler argument and returns a Delegate :
public void AddHandler<Handler>(Control c, string eventName, Func<Delegate, Handler> convert, Handler d) { c.GetType().GetEvent(eventName).AddEventHandler(c, convert(d)); }
Now the compiler is happy. The method call is simple. For example, attaching to a KeyPress event in a Windows Forms control:
AddHandler<KeyEventHandler>(someControl, "KeyPress", (h) => (KeyEventHandler) h, SomeControl_KeyPress);
where SomeControl_KeyPress is the purpose of the event. The key is the lambda converter - it does not work, but it convinces the compiler that you gave it a valid delegate.
(Start 280Z28) @Justin: Why not use this?
public void AddHandler<Handler>(Control c, string eventName, Handler d) { c.GetType().GetEvent(eventName).AddEventHandler(c, d as Delegate); }
(end 280Z28)
Justin Bailey Jan 18 '10 at 18:30 2010-01-18 18:30
source share