Saturday, January 14, 2006

hook up a Delegate to a method obtained through reflection

I've been looking for this and finding people with the same problem, and the answers I found all were

"use Delegate.CreateDelegate"

sure, that's the answer, but what parameters or what do I pass to it?

the closest thing I found to a complete answer was this article
http://msdn2.microsoft.com/en-us/library/ms228976.aspx

but the answer was not quite clear, so here it is, hopefully simple enough to be of help for you

//*** these are required to load the assembly
object instance;
Type type;
//*** declare the Delegate (the pointer to the method obtained through reflection)
Delegate GenericMethod;
//*** declare the delegate signature
delegate string StringMethod(string name);


//*** load the assembly (you need include System.Reflection)
Assembly asm = Assembly.LoadFile(@"f:\ScriptLibrary.dll");
type = asm.GetType("ScriptLibrary.ScriptClass", true);
instance = Activator.CreateInstance(type);
//*** hook up the delegate to the method

GenericMethod = Delegate.CreateDelegate(typeof(StringMethod), instance, "method1");

//*** calling the method through the delegate
string s;
s = (string)GenericMethod.Method.Invoke(instance, new object[] {(string)"Eber"});


why would you want to load the method in a delegate instead of using InvokeMember?
according to Eric Gunnerson
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp02172004.asp

is much faster to use a delegate, than to use InvokeMember

by the way, on his article he didn't use a MethodInfo, which is close in speed to the delegate

so...
delegate - fastest
MethodInfo - close to the delegate speed
InvokeMember - slowest

hope this helps

No comments: