views:

39

answers:

1

So, i have an assembly that i loaded into the interface, and it works perfectly:

MarshalByRefObject pluginObject = ...
ecko.Plugins.Interface.Plugin plug = pluginObject as ecko.Plugins.Interface.Plugin;

but, allthough i will have alot of methods in the interface, i will have to execute methods that are dynamic, and determined from information in the interface.. so basically, i need to call methods that are not in my interface, and i wont know the name of until last minute..

this is what i have tried (using the "Execute" methods as an example):

 plug.GetType().GetMethod("Execute").Invoke((what-the-hell-do-i-put-here), new object[] { });

am i on the right track? please guide me :)

thanks.

+1  A: 

If you want to use Reflection then the missing piece in your code is:

 MethodInfo meth = plug.GetType().GetMethod("Execute");
 meth.Invoke(plug, new object[] { }); 

The first parameter of the Invoke method should be the instance that you want to invoke the method on. This is required because meth is just an abstract description of the method (and is not associated with any instance). This is useful if you want to call the method on multiple instances (you could cache the meth value).

If you're using C# 4.0, then you can use the new dynamic feature (assuming that "Execute" is a name that does not change):

dynamic plugDynamic = plug;
plugDynamic.Execute( /* arguments */ );

If a variable is declared as dynamic in C# 4.0, then you can call any methods you want and the method resolution will be done at runtime (similar to Reflection, but a bit more complicated and a bit more efficient).

Tomas Petricek
I actually get "Object reference not set to an instance of an object." here: http://prntscr.com/syxs
Tommy