In some application scenarios, We need to dynamically call methods in some assemblies, such as the functions of integrating sub-products, sub-projects, or third-party products in some large products, one way is through data persistence. data persistence may use relational databases or XML to store Assembly names, namespaces, class names, method names, parameter types, and values, in this way, we can make a very good decoupling component through reflection combined with business logic. Persistence and business logic are not considered here, but a demo is just introduced to realize dynamic calling of methods in DLL using reflection. The main steps are summarized as follows:
1. Get the Assembly file name or path and load the Assembly;
Assembly = NULL; string apppath = assembly. getexecutingassembly (). location; apppath = apppath. substring (0, apppath. lastindexof ('\') + 1); // 1. Get the Assembly file name or path, and load Assembly = assembly. loadfrom (apppath + "factrefect. DLL ");
2. Obtain the system. Type object with the specified name in the Assembly instance;
Type type = NULL; // 2. Obtain the system. Type object type = assembly. GetType ("factrefect. refectiontest") with the specified name in the Assembly instance ");
3. Obtain the target class instance of type;
Object OBJ = NULL; // 3. Obtain the target class instance OBJ = type. invokemember (null, bindingflags. declaredonly | bindingflags. public | bindingflags. nonpublic | bindingflags. instance | bindingflags. createinstance, null );
4. Call methods in a type instance;
// 4. First call the Set Method in the refectiontest class and set the values of X and Y to 1 and 2 types, respectively. invokemember ("set", bindingflags. declaredonly | bindingflags. public | bindingflags. nonpublic | bindingflags. instance | bindingflags. invokemethod, null, OBJ, new object [] {1, 2}); // 5. Call the show method in the refectiontest class to print the x and y values. invokemember ("show", bindingflags. declaredonly | bindingflags. public | bindingflags. nonpublic | bindingflags. instance | bindingflags. invokemethod, null, OBJ, null );
Download demo source code: refectiontest.zip