I have always wanted to learn plug-in programming. The main reason is that my current customer needs are changing. If I integrate all the functions into an execution file, it is inconvenient to modify and upgrade, to use plug-in programming, you only need to buildProgramAfter the framework, each time a function is completed, the user can review it and convert it to zero, so that both the development team and the customer can grasp the progress of project development. at the same time, you can use this method to enhance your confidence in project completion on time.
The following materials are mainly obtained from the Haha blog. I have found many similar materials on the Internet. I think this is the best choice for beginners.
// 1. Define the plug-in interface and compile it into a DLL, for example:
Using System;
Namespace Plugininterface
... {
Public InterfaceIshow
...{
StringShow ();
}
}
// 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 StringShow ()
...{
Return "I am plugin";
}
}
}
Collection assembly:
// 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 to 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 );
}
}
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. Use reflection to construct DLL file instances
System. reflection. Assembly ASM = System. reflection. Assembly. loadfrom (asmfile );
// 3. Use reflection to extract classes from the Assembly (DLL) and instantiate these 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 );
}
}
Of course, this routine has no practical value, but it is very simple and clear.
If you want to develop an application plug-in, you must add custom attributes and other constraints.