C # Use reflection to load multiple sets,
Reflection is required when developing plug-ins. The traversal assembly is dynamically loaded on the client and the methods of each Assembly are called.
To create a console application, first design an interface:
public interface ISay { void SaySth(); }
Create the Plugins folder under the console application. The executable files in the console and all Assembly files are generated here. Right-click the console project -- "properties" -- "generate" and set "output path" to the Plugins folder.
Create a class library project Assembly1, add a reference to the console project, and create a class that implements the ISay interface:
Namespace Assembly1 {public class OneSay: ISay {public void saything () {Console. WriteLine ("I'm from Assembly 1 ");}}}
Right-click the class library project Assembly1 -- "attribute" -- "generate", set "output path" to the Plugins folder, and generate the class library project Assembly1.
The client needs to find all classes that implement the ISay interface in all datasets. The basic idea is:
→ Find all dll Suffixes in the Plugins folder
→ Traverse these files and dynamically load the Assembly according to the file name
→ Implement the ISay interface type in the traversal set and save it to the ISay type set.
→ The client traverses the ISay type set and calls the ISay interface method.
Class Program {static void Main (string [] args) {foreach (var say in GetSpeakers () {say. sayth () ;}} static List <ISay> GetSpeakers () {List <ISay> result = new List <ISay> (); // obtain the Plugins folder string dir = Directory under the root Directory of the project. getCurrentDirectory (); // traverses the file foreach (var file in Directory. getFiles (dir + @"\","*. dll ") {// load the Assembly var asm = Assembly. loadFrom (file); // traverses the type foreach (var typ) in the Assembly E in asm. getTypes () {// if it is an ISay interface if (type. getInterfaces (). contains (typeof (ISay) {// create an interface type instance var isay = Activator. createInstance (type) as ISay; if (isay! = Null) {result. Add (isay) ;}}} return result ;}
Create a class library project Assembly2, add a reference to the console project, and create a class that implements the ISay interface:
Namespace Assembly2 {public class TwoSay: ISay {public void saything () {Console. WriteLine ("I'm from assembly 2 ");}}}
Right-click the class library project Assembly2 -- "attribute" -- "generate", set "output path" to the Plugins folder, and generate the class library project Assembly2.
Run the console project again.