CreateDelegate for and type of EventArg

R

redhotsly

Hi,

Is is possible to create an event handler method that can handle any
type of event no matter what the delegate signature is.

Here is the code I have so far:

public class class1
{
public Delegate Hook(Type eventHandlerType)
{

Delegate eh = Delegate.CreateDelegate(
eventHandlerType,
this,
"Callback",
true );

return eh;

}

private void CallBack(object sender, EventArgs e)
{
Console.WriteLine("callback");
}
}


With the code above I can do:

Delegate d = _class1.Hook( typeof( EventHandler ) );
d.Method.Invoke(...);


But I cannot do it with other type of delegates, such as
CancelEventHandler:

Delegate d = _class1.Hook( typeof( CancelEventHandler ) );
d.Method.Invoke(...);

This fails at runtime. The call to Delegate.CreateDelegate fails with
an argument exception. Error: "Error binding to target method."

Is there a way to this work? After all CancelEventArg derives from
EventArg.

Thanks for your help.

Sylvain
 
N

Nicholas Paldino [.NET/C# MVP]

Unfortunately, in .NET 1.1 and before, there is not. However, in .NET
2.0 and beyond, yes, you can do this, because there is covariance with
delegate parameters (meaning that because your method handler can accept
EventArgs, and that is the base class for the parameters required by the
delegate).

Hope this helps.
 
M

Mattias Sjögren

Is there a way to this work? After all CancelEventArg derives from
EventArg.

You can generate dynamic thunk methods with Reflection Emit that
matches the delegate signature and forwards the call to a generic
handler. Pretty messy but doable.



Mattias
 

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