C # reflection tutorial (2)

Source: Internet
Author: User

Analysis

Reflection technology can be obtained at runtimeProgramSet members of each type, including fields, methods, attributes, and events, and further obtain detailed information about these members. Reflection technology can also dynamically load external assembly (private assembly or shared Assembly) to obtain related data of the assembly type. It is interesting that an assembly dynamically loaded from the outside can also be bound late to create an instance (object) of a certain type in the external assembly, and can further call its members (such as methods and attributes ). In this process, you do not know any information about the external assembly (or even whether the Assembly exists ).

In short, the reflection technology uses the programming method to obtain the metadata of the program set. In general, the ildasm.exe program can only load the assembly or module to read its metadata. Net reflection technology obtains various detailed type metadata from the program set (for example, the fieldinfo class describes the details of the Field) instances and performs further operations. Most of these detail types belong to the system. reflection namespace.

Description: ildasm.exe is a program of the. NET Framework. It is used to view the Il of the Assembly.CodeAnd metadata. Assume that the C drive is a system partition, so the ildasm.exe program is usually located in the C:/Windows/Microsoft. NET/framework/v2.0.50727 directory.

The system. Reflection namespace contains many reflection-related types that can be used to obtain all the details of a specified type. This question requires to obtain complete information about the methods of the specified type, while system. in the reflection namespace, the methods are of the methodinfo type and parameterinfo type. Therefore, you only need to obtain the objects related to the two classes of the methods in the specified type. To achieve this purpose, you need to obtain the type object that represents the specified type of metadata. The type object is system. type class instance. Members of this object can return system. types in the reflection namespace, including the methodinfo type and parameterinfo type. In the previous example, the GetType method of the object is used to obtain the type name. In addition, there are multiple methods to obtain the type object, as shown in the following code:

+ Expand

{
Codeop (this)
} ">-C # // Call the GetType method of the object to obtain the reference of the type object
Type object reference variable = object. GetType ();
// Call different overloaded versions of the Type-class GetType static method
Type object reference variable = system. type. GetType ( "Type decoration name" );
Type object reference variable = system. type. GetType ( "Type decoration name" ,
Whether to throw an exception, Case Insensitive );
Type object reference variable = system. type. GetType ("type decoration name,
Friendly name of the Assembly to which the type belongs ");
// Use the typeof operator of C #
Type object reference variable = Typeof (Type name );

The above code calls the GetType () Static Method of the type class. Among them, the 3rd overloaded versions are used to obtain the type object of the external private assembly type. After obtaining a type object of the specified type, you can return the methodinfo type and parameterinfo type through its members to obtain the complete information of the method, as shown in the following code:

+ Expand

{
Codeop (this)
} ">-C # Using System;
Using System. reflection;

Methodinfo [] method array = type. GetType ("Type decoration name",False,False);
Use the foreach statement to traverse each sub-item of the method array to access all information of the methods in the type;
// In the foreach statement, call the getparameters method of the sub-item of the method array to return the parameter array of the parameterinfo type.
Parameterinfo parameter array = method array subitem. getparameters ();
Use the foreach statement to traverse each sub-item of the parameter array to access all the information of parameters in the method;

The preceding Code uses the foreach statement to access all the parameters in the method.

Note: by default, reflection can only obtain information about public members, but access to non-public members may pose security risks. Therefore, the code for accessing non-public members requires a reflectionpermission with the appropriate flag. In addition, securitypermission is required for some tasks (such as executing unmanaged code and serialized objects.

Interview Example 7: How to Use reflection to obtain information of the specified type of the current Assembly?

Test site: the method used by the reflection technology to obtain the type information and the method used to obtain the type member set.

Frequency:★★

Answer

To obtain information of a specified type, you only need to obtain the type object of this type and then call its members. Obtain the Execution Code encapsulated in the static method REF () of the classb class. The user inputs different values to reflect different types of details. Create a program file in the directory and name it classref. cs. Write the code as shown in code 7.7.

Code 7.7 reflects information of the specified type: classref. CS

+ Expand

{
Codeop (this)
} ">-C # Using System;
// Import the corresponding namespace
Using System. reflection;

Class Classref
{
Static Void Main ( String [] ARGs)
{
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 ;
}
Try
{
// Call the static method GetType of the type class and return the type object reference to the TP variable
Type TP = type. GetType (input, False , False );
// Call the static ref method of classb and pass the TP object
Classb. Ref (TP );
}
// 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 );
}
}
}
}
// Define two interface types: iclassa and iclassb
Public Interface Iclassa
{
String Methoda ( String S );
}
Public Interface Iclassb
{
String Name
{
Get ;
}
}
// Defines classa, which inherits from the interface types iclassa and iclassb
Class Classa : Iclassa, iclassb
{
Public String _ Name;
Public String Name
{
Get
{
Return _ Name;
}
}
// Define the methoda method for internal Permissions
Public String Methoda ( String S)
{
_ Name = s;
Return _ Name;
}
// Define the methodb method with the public permission
Public Classa ( String S)
{
Console. writeline ( "The received parameter is: {0 }" , S );
}
}
Class Classb
{
String _ Name;
// Define the methodb method for internal Permissions
Internal String Methodb ( String S)
{
_ Name = s;
Return _ Name;
}
// Defines the static method ref and receives one type parameter.
Public Static Void Ref (type TP)
{
// Output basic attributes of the type object
String Fullname = TP. fullname;
Console. writeline ( "/N/T ================={ 0} type information ================" , Fullname );
Console. writeline ( "{0} is a generic type? -> {1 }" , Fullname, TP. isgenerictype );
Console. writeline ("{0} is the interface type? -> {1 }" , Fullname, TP. isinterface );
Console. writeline ( "{0} is it a class type? -> {1 }" , Fullname, TP. isclass );
Console. writeline ( "{0} is a COM object? -> {1 }" , Fullname, TP. iscomobject );
Console. writeline ( "{0} is the public access type? -> {1 }" , Fullname, TP. ispublic );
Console. writeline ( "{0} is the seal type? -> {1 }" , Fullname, TP. issealed );
Console. writeline ("{0} is it a value type? -> {1 }" , Fullname, TP. isvaluetype );
// 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 interfaces supported by the Type object and save the interfaces to the administrator privilege array.
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 );
}

}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.