Create delegate from MethodInfo

M

Mike Scott

Given a MethodInfo for a static method (found using a custom attribute), I
want to create a delegate for it.

However, Delegate.CreateDelegate isn't supported on the Compact Framework
:-(

Does anyone know how to do this in C#?

Cheers,

MikeS.
 
J

Jonathan Wells [msft]

M

Mike Scott

Hi Jonathan

Thanks for the link - but it's not what I'm looking for. Using interfaces is
what I'm doing at the moment, and I want to switch to using delegates. I
don't really want to have a class per method that I need to call. It's a
communications app and I want to be able to handle a set of messages, with
each message having a unique integer ID. I have a Hashtable into which I
insert a message handling delegate keyed by the message type ID. Using
reflection allows me easily to add new message handlers without having to
modify any existing code - I just add a method decorated with my custom
MessageHandlerAttribute. But the furthest I can get is to a MethodInfo. I
can't figure out a way to create the delegate dynamically.

However, I've worked around the missing Delegate.CreateDelegate() by
creating a small adapter class that takes the MethodInfo as a parameter to
its constructor. The class has a method which conforms to the delegate
signature so I just create a delegate to this method. This then just makes
the call on to the method that was discovered using reflection using
MethodInfo.Invoke.

Although Delegate.CreateDelegate() is missing on the CF, I was hoping there
was another way (e.g. using some other class) to create a delegate. It must
be possible - after all C# does it. Maybe I'll have to write some IL?

Cheers,

Mike.
 

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