Instantiate the class based on the class name string and call the class method or function
// Obtain the type information
// If you call another DLL
// System. reflection. Assembly ASMB = system. reflection. Assembly. loadfrom ("DLL name ");
// Type T = ASMB. GetType ("Class Name ");
// If other DLL is not called
System. reflection. Assembly BLL = system. reflection. Assembly. Load ("www. www. BLL ");
System. type T = BLL. GetType ("www. www. BLL." + viewstate ["BLL"]. tostring ());
Try {
// Create a type instance
Object dobj = activator. createinstance (t );
// Obtain method information
System. reflection. methodinfo method = T. getmethod ("delete ");
// Call some flag spaces of the method (set according to the flag of your method)
System. reflection. bindingflags flag = system. reflection. bindingflags. Public | system. reflection. bindingflags. instance | system. reflection. bindingflags. Static;
// Method parameters
Object [] parameters = new object [] {Int. parse (viewstate ["ID"]. tostring ())};
// Obtain the value returned by the method
Object returnvalue = method. Invoke (dobj, flag, type. defaultbinder, parameters, null );
}
Catch (system. Exception ex ){}
Note:
Assembly = assembly. LoadFile ("ProgramSet path, cannot be relative path "); // load the Assembly (exe or DLL)
Object OBJ = assembly. createinstance ("fully qualified class name (including namespace)"); // create a class instance
To reflect the classes in the current project, you can:
Assembly = assembly. getexecutingassembly (); // get the current Assembly
Object OBJ = assembly. createinstance ("fully qualified class name (including namespace)"); // creates a class instance and returns the object type, which requires forced type conversion.
It can also be:
Type type = type. GetType ("Full qualified name of the class ");
Object OBJ = type. Assembly. createinstance (type );
Supplement:
1) when reflecting the creation of an instance of a class, you must ensure that the fully qualified name (namespace + class name) of the class is used ). If the type. GetType method returns NULL, the related information in the search metadata fails (reflection fails). Make sure to use the fully qualified name of the class during reflection.
2) The reflection function is very powerful and there is nothing to do.
"Cross-Assembly" (as shown below), please use the first method I gave to create a class instance and reflect the fields, attributes, methods, events of the instance... and then call it dynamically.
Reflection actually uses the metadata of the Assembly.
There are many methods for cross-assembly reflection. When writing a program, pilot the system. reflection namespace. Suppose you want to reflect the class in a DLL without referencing it (that is, unknown type ):
Assembly = assembly. LoadFile ("assembly path, cannot be relative path"); // load the Assembly (exe or DLL)
Object OBJ = assembly. createinstance ("fully qualified class name (including namespace)"); // create a class instance