Reputation: 321
I have a DLL containing some methods (show, hide and validate). Here is an example of one of the methods hide(Panel paneldynamic, String id, List<EventActions> eventList)
. All methods contains the same parameters.
Now I have referenced the my DLL on my main form, how can I dynamically invoke one of the methods at runtime?
Upvotes: 5
Views: 17070
Reputation: 64
You can get type by Reflection and invoke method like this:
type.InvokeMember("hide", BindingFlags.InvokeMethod | BindingFlags.Static |
BindingFlags.Public, null, null, new object[] { paneldynamic, id, eventList });
Upvotes: 1
Reputation: 112324
Insert your methods as delegates into a dictionary
public enum MethodType
{
None,
Show,
Hide,
Validate
}
var methods = new Dictionary<MethodType, Action<Panel, String, List<EventActions>>();
methods.Add(MethodType.Show, show);
methods.Add(MethodType.Hide, hide);
methods.Add(MethodType.Validate, validate);
Then you can invoke one of them with
MethodType methodToInvoke = MethodType.Hide;
methods[methodToInvoke](paneldynamic, id, eventList);
If you intend to dynamically load the DLL, this is another story. You will need at least three assemblies (three projects): one main assembly (exe), one contract assembly (dll) and one plug-in assembly (dll). The main and the plug-in assembly both have to reference the contract assembly. The contract assembly contains an interface
public interface IPlugIn
{
void Show(Panel paneldynamic, String id, List<EventActions> eventList);
void Hide(Panel paneldynamic, String id, List<EventActions> eventList);
void Validate(Panel paneldynamic, String id, List<EventActions> eventList);
}
The plug-in assembly contains a class implementing the interface
public class PlugIn : IPlugIn
{
// TODO: implement IPlugIn
}
In the main assembly you can load the plug-in like this
IPlugIn LoadPlugInFromFile(string fileName)
{
Assembly asm = Assembly.LoadFrom(fileName);
Type type = asm.GetType("PlugIn");
IPlugIn plugIn = (IPlugIn)Activator.CreateInstance(type);
return plugIn;
}
Invoke like this
IPlugIn plugIn = LoadPlugInFromFile("C:\PlugIns\MyPlugIn.dll");
plugIn.Show(paneldynamic, id, eventList);
Upvotes: 4
Reputation: 224905
You'll need to use reflection. First, load the assembly (note that this assumes you've imported System.Reflection
):
Assembly a = Assembly.LoadFile(pathToTheDll);
Get the type containing the method by fully-qualified name:
Type t = a.GetType("Some.Class");
Now, get the method:
MethodInfo m = t.GetMethod("hide"); // For example
Then, all you have to do is invoke it:
m.Invoke(null, new object[] { /* parameters go here */ });
The first argument to Invoke
is the instance. If your class is static
, use null
, otherwise, you'll need to supply an instance of the type created using Assembly.CreateInstance
.
Upvotes: 17