// 1 Define the plug-in interface and compile it into a DLL, for example:
Using system;
Namespace plugininterface
{
Public interface ishow
{
String show ();
}
}
// 2 compile the plug-in. Create a DLL project and reference the DLL plug-in step 1 to implement its interface, for example:
Namespace plugina
{
Public class plugina: plugininterface. ishow
{
Public String show ()
{
Return "I am plugin ";
}
}
}
2. Collect or load plug-ins in the main program
// 3. Find the DLL file in the specified directory
Private void frmmain_load (Object sender, system. eventargs E)
{
// Obtain all DLL files in the Plugins directory and save them in combo.
Try
{
String Path = application. startuppath;
Path = system. Io. Path. Combine (path, "plugins ");
Foreach (string file in system. Io. Directory. getfiles (path, "*. dll "))
{
This. cmbplugins. Items. Add (File );
}
}
Catch (exception ex)
{
MessageBox. Show (ex. Message );
}
}
3. Use plug-ins
Private void btnexecute_click (Object sender, system. eventargs E)
{
Try
{
// 1. Get the file name
String asmfile = This. cmbplugins. text;
String asmname = system. Io. Path. getfilenamewithoutextension (asmfile );
If (asmfile! = String. Empty)
{
// 2. Construct the DLL file instance Using Reflection
System. reflection. Assembly ASM = system. reflection. Assembly. loadfrom (asmfile );
// 3. Use reflection to extract classes from the Assembly (DLL) and instantiate the classes.
Plugininterface. ishow = (plugininterface. ishow)
System. activator. createinstance (ASM. GetType (asmname + "namespace." + asmname + "class "));
// 4. Use the instance of this class in the main program
This. label2.text = ishow. Show ();
}
}
Catch (exception ex)
{
MessageBox. Show (ex. Message );
}
}