Interview Example 8: How to dynamically load externalProgramSet and use reflection to obtain information of the specified type?
Test site: learn the basic methods for dynamically loading external assembly and understand the differences between the load () method and loadfrom () method of the Assembly class.
Frequency:★★★
Answer
The Assembly class in the system. Reflection namespace can dynamically load external assembly. The optional methods are the load () method and loadfrom () method. The load () method is used to load the external assembly in the same directory of the current Assembly. The loadfrom () method can load the Assembly in other directories. The classref.exe program in the preceding example is used as the external assembly to be loaded to further obtain information of the specified type. Create a program file in the directory and name it appclassref. CS.CodeShows code 7.8.
Code 7.8 dynamically loads an external assembly:
+ Expand
{
Codeop (this)
} ">-C # Using System;
// Import the corresponding namespace
Using System. reflection;
Using System. IO;
Class Appclassref
{
Static Void Main ( String [] ARGs)
{
// View all the assemblies in the current application domain
Disallam ();
While ( True )
{
Console. Write ( "Enter the detected type name :" );
// Receives user input values and assigns them to input variables
String Input = console. Readline ();
// If the user inputs "quit", the loop jumps out.
If (Input = "Quit" )
{
Break ;
}
// Declare the assembly type object AM
Assembly am;
Try
{
// Call the load method of the Assembly class to pass the reference to AM
AM = assembly. Load ( "Classref" );
// The following code calls the loadfrom method of the Assembly class
// AM = assembly. loadfrom (@ "D:/web/NET/classref.exe ");
// Call the GetType method of AM and return the type object reference to the TP variable
Type TP = aM. GetType (input, False , False );
// Call the static ref method of classb and pass the TP object
Classb. Ref (TP );
}
// An error occurred while capturing the file.
Catch (Filenotfoundexception E)
{
// Output exception information
Console. writeline ( "Exception information: {0 }" , E. Message );
}
// Catch Null Object reference exception
Catch (Nullreferenceexception E)
{
// Output exception information
Console. writeline ( "Exception information: {0 }" , E. Message );
}
// Catch General Exceptions
Catch (Exception E)
{
// Output exception information
Console. writeline ( "Exception information: {0 }" , E. Message );
}
Finally
{
// View all the assemblies in the current application domain again
Disallam ();
}
}
}
// Define the disallam method to display the Assembly List
Static Void Disallam ()
{
Console. writeline ( "/N/T =============== all loaded assemblies in the current application domain ================" );
// Use the getassemblies method to obtain all the assemblies in the current application domain
Foreach (Assembly In Appdomain. currentdomain. getassemblies ())
{
// Output Assembly name
Console. writeline ( "Assembly: {0 }" , A. fullname );
}
}
}
Class Classb
{
// Define the static method ref to receive a type parameter
Public Static Void Ref (type TP)
{
// Output basic attributes of the type object
String Fullname = TP. fullname. tostring ();
Console. writeline ( "/N/T ================={ 0} type information ================" , Fullname );
// Obtain all public members of the type object and save them to the MI array.
Memberinfo [] MI = TP. getmembers ();
// Traverse and output all sub-item attributes of the MI Array
Foreach (Memberinfo m In Mi)
{
Console. writeline ( "/T member category-> {0}, name-> {1 }" , M. membertype, M. Name );
}
// Obtain the interface implemented by the Type object and save it to the Administrator list
Type [] IBD = TP. getinterfaces ();
// Determine whether the dataset has subitems. If so, the subitem attribute is output.
If (IBD. length! = 0)
{
Foreach (Type T In (UI)
{
Console. writeline ( "{0} implemented interface type-> {1 }" , Fullname, T. fullname );
}
}
Else
{
Console. writeline ( "Any interface types not implemented by {0" , Fullname );
}
}
}
The output information of this topic is the same as that of classref.exe. The main program first calls the disallam () static method, which encapsulates the code for listing the Assembly List contained in the current application domain. Compile appclassref. CS in the command line to execute the appclassref program. The running result is 7.13.
This program first outputs the list of the assemblies contained in the current application domain. It can be seen that only the mscorlib assembly and the appclassref assembly are loaded. Continue and call the disallam () method again. The classref assembly has been added to the output assembly list.
Figure 7.13 dynamic loading of external assembly
Note:Mscorlib Assembly contains most of the base class libraries of. Net, which are automatically loaded during CLR runtime.
Analysis
The program dynamically loads the external Assembly through the Assembly class in the system. Reflection namespace. The load () method and the loadfrom () method of this class can load the specified external assembly at runtime. After an external assembly is loaded, the Assembly class creates an object and calls the GetType () method of the object to obtain detailed information of the specified type. Assume that the myapp.exe assembly under D:/root directory is loaded and the Assembly Class Object am is defined, as shown in the following code:
The detailed information of the classa class is directly output in sequence. Input "classb" again, and the program outputs the details of the classb class. The running result is 7.10.
+ Expand
{
Codeop (this)
} ">-C # Using System;
// Import the corresponding namespace
Using System. reflection;
Using System. IO;
Assembly am;
Try
{
AM = assembly. Load ("MyApp");
Type TP = aM. GetType ("Specified type name",False,False);
}
Catch(Filenotfoundexception E)
{
Console. writeline ("Exception information: {0 }", E. Message );
}
The above code calls the load () method of the Assembly class to load the MyApp assembly (exe or DLL). The premise of normal code loading is that the current Assembly and MyApp Assembly are in the same directory. Therefore, the loadfrom () method of the Assembly class is also commonly used. The compiling method is as follows:
+ Expand
{
Codeop (this)
} ">-C # Am = assembly. loadfrom ( "D:/myapp.exe" );
It can be seen that the loadfrom () method of the Assembly class must pass the complete path of the external assembly. After the external assembly is loaded, you can access the Assembly contained in the current application domain to determine whether the load is successful. Note the import of the system. Io namespace because the exception "file not found" needs to be caught in the main program to prevent external assembly from existent.
Description: reads the currentdomain attribute of the appdomain class, returns the current application domain, and calls the getassemblies method of the current application domain to obtain the set of included assemblies.
Interview Example 9: How to bind a call method member through the late stage?
Test site: the meaning of late binding and the basic method of late binding.
Frequency:★★★
Answer
Late binding means you cannot determine whether a type exists during compilation. You can create an instance of this type at runtime and call its members. In this example, the program defines three external types, which are compiled into DLL assembly. The latebinding. CS code dynamically loads the program and calls its internal methods. Create a program file in the directory and name it oldclass. cs. Write the code as shown in code 7.9.
Code 7.9: 1st external classes: oldclass. CS
+ Expand
{
Codeop (this)
} ">-C # Public Class Oldclass
{
// Define the static method of public permission
Public Static String Method ( String S)
{
String Output = "The method static method of the oldclass class returns the result :" + S;
Return Output;
}
}
Create a program file in the directory and name it newclass. cs. Write the code as shown in code 7.10.
Code 7.10: 2nd external classes: newclass. CS
+ Expand
{
Codeop (this)
} ">-C # Public Class Newclass
{
// Defines the Method Instance method with the public permission
Public String Method ( String S)
{
String Output = "Result returned by the Method Instance method of the newclass class :" + S;
Return Output;
}
}
Create a program file in the directory and name it myclass. cs. Write the code as shown in code 7.11.
Code 7.11: 3rd external classes: myclass. CS
+ Expand
{
Codeop (this)
} ">-C # Public Class Myclass
{
// Defines the Method Instance method with the public permission
Public String Method ( String S)
{
String Output = "Result returned by the Method Instance method of the myclass class :" + S;
Return Output;
}
// Define the methodtxt instance method with the public permission
Public String Methodtxt ()
{
String Output = "The methodtxt of the myclass class has no parameter. The instance method is called" ;
Return Output;
}
}