Reflection post in C)

Source: Internet
Author: User

Reflection Overview

Reflection definition: the ability to review metadata and collect information about its type. Metadata (the most basic data unit after compilation) is a lot of tables.ProgramWhen a set or module is used, the compiler creates a class definition table, a field definition table, and a method definition table ,. The system. Reflection namespace contains several classes that allow you to reflect (PARSE) the metadata tablesCodeReflection-related namespaces (we access reflection information through these namespaces ):

System. reflection. memberinfo

System. reflection. eventinfo

System. reflection. fieldinfo

System. reflection. methodbase

System. reflection. constructorinfo

System. reflection. methodinfo

System. reflection. propertyinfo

System. Type

System. reflection. Assembly

Function of reflection:

1. You can use reflection to dynamically create instances of the type, bind the type to an existing object, or obtain the type from an existing object.

2. The application needs to load a specific type from a specific program set at runtime, so that reflection can be used for a task.

3. Reflection main applications and class libraries. These class libraries need to know a type definition to provide more functions.

Application highlights:

1. In real applications, few applications need to use the reflection type.

2. dynamic reflection binding sacrifices Performance

3. Some metadata information cannot be obtained through reflection.

4. Some reflection types are specifically used for the development and use of CLR development compilers, so you must realize that not all reflection types are suitable for everyone.

Assembly that reflects appdomain

When you need to reflect all the Assembly contained in the appdomain, the example is as follows:

 

Static   Void Main
... {
// Call all the assembly of appdomain through getassemblies
Foreach (Assembly assem In Appdomain. currentdomain. getassemblies ())
... {
//Reflects information about the current Assembly.
Reflector. reflectonassembly (assem)
}
}

Note: The getassemblies method of the appdomain object will return an array composed of system. reflection. Assembly elements.

Reflection of a single assembly

The above method is used to reflect all the assembly of the appdomain. We can display the call to one of the Assembly. The system. reflecton. assembly type provides the following three methods:

1. load Method: a highly recommended method. The load method carries an Assembly flag and loads it. Load will cause the CLR to apply the policy to the Assembly, which is successively in the global assembly buffer, find the Assembly under the application base directory and private path. If the Assembly cannot be found, the system throws an exception.

2. loadfrom method: Pass the path name (including the extension) of an assembly file. CLR loads the specified assembly. The passed parameter cannot contain any information about the version number, culture, and public key information. If the Assembly cannot be found in the specified path, an exception is thrown.

3. loadwithpartialname: never use this method, because the application cannot determine the version of the loaded assembly. The only purpose of this method is to help customers who use a certain behavior provided by the. NET Framework in the testing stage of the. NET Framework. This method will eventually be discarded.

Note: system. appdomain also provides a load method, which is different from the static load method of assembly. The load method of appdomain is an instance method, and a reference to the Assembly is returned, the static load of Assembly sends the Assembly value encapsulation back to the appdomain that sends the call. avoid using the appdomain load method whenever possible

Obtain type information using reflection

After talking about Assembly reflection, let's talk about the third layer in the reflection hierarchy model, type reflection.

A simple example of retrieving type information using reflection:

Using System;

Using Sytem. reflection;

Class Reflecting
... {

Static   Void Main ( String [] ARGs)
... {
Reflecting reflect = New Reflecting (); // Define a new class

// Call a reflecting.exe assembly

Assembly myassembly = Assembly.loadfrom(“reflecting.exe ")

Reflect. getreflectioninfo (myassembly ); // Obtain reflection Information
}

// Define a method to obtain the reflected content
Void Getreflectioninfo (Assembly myassembly)
... {

Type [] typearr = Myassemby. gettypes (); // Retrieve type

Foreach (Type type In Typearr) // Obtain detailed information for each type
... {

// Obtain structure information of a Type
Constructorinfo [] myconstructors = Type. getconstructors;

// Obtain field information of the type.
Fieldinfo [] myfields = Type. getfiedls ()

// Obtain method information
Methodinfo mymethodinfo = Type. getmethods ();

// Get property information
Propertyinfo [] myproperties = Type. getproperties

// Obtain event information
Eventinfo [] myevents = Type. getevents;
}
}
}

Other methods for getting type objects:

1. The system. Type parameter is of the string type. The full name of the type (including its namespace) must be specified for this string)

2. system. Type provides two instance methods: getnestedtype and getnestedtypes.

3. The instance methods provided by syetem. reflection. Assembly are GetType, gettypes, and getexporedtypes.

4. system. reflection. Moudle provides these instance methods: GetType, gettypes, findtypes

Set reflection type members

The member of the reflection type is the bottom layer of data in the reflection hierarchy model. We can use the getmembers method of the type object to obtain a type member. If we use getmembers without parameters, it only returns static variables and instance members of the public definition of this type, you can also use getmembers with parameters to return the specified type members through parameter settings. For more information about the parameters, see system. reflection. bindingflags Enumeration type in msdn.

For example:

// Set the member content of the type to be returned

Bindingflags BF = bingdingflags. declaredonly | bingdingflags. nonpublic | bingdingflags. Public;

Foreach (memberinfo mi int T. getmembers (BF ))
{
Writeline (MI. membertype) // output the specified type member
}

Create a type of instance through reflection

Through reflection, we can get the assembly type. We can create a new instance of this type based on the obtained assembly type. This is also the function of late binding when an object is created at runtime.

We can achieve this through the following methods:

1. createinstance method of system. activator. This method returns the reference of the new object. For more information, see msnd.

2. The createinstancefrom of system. activator is similar to the previous method, but the type and its assembly must be specified.

3. Method of system. appdomain: createinstance, createinstanceandunwrap, createappsancefrom and createappsacefromandunwrap

4. invokemember instance method of system. Type: This method returns a constructor that matches the input parameter and constructs this type.

5. system. reflection. constructinfo invoke instance method

Reflection interface

If you want to obtain a set of all interfaces inherited by the type, you can call findinterfaces getinterface or getinterfaces of the type. All these methods can only return directly inherited interfaces of this type. They do not return interfaces inherited from an interface. To return the basic interface, you must call the preceding method again.

Reflection performance:

When Using Reflection to call a type or trigger method, or when accessing a field or attribute, CLR needs to do more work: Check parameters, check permissions, and so on, so the speed is very slow. Therefore, do not use reflection for programming. You can use the following methods to write a dynamic Constructor (late binding:

1. inherit from the class. Let this type be derived from a known basic type during compilation, generate an instance of this type at runtime, and place its reference to a variable of its basic type, then, call the virtual method of the basic type.

Original article:

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.