Step by Step C # technical discussion 1. reflection mechanism

Source: Internet
Author: User

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. When compiling an assembly or module, the compiler creates a class definition table and a field definition table, and a method definition table.

The Common Language Runtime Library (CLR) loader manages application domains that form a definite boundary around objects with the same application scope. Such management includes loading each assembly to the corresponding application domain and controlling the memory layout of the type hierarchy of each set.
The System. reflection namespace contains several classes that allow you to reflect (PARSE) the Code of these metadata tables
System. Reflection. Assembly
System. Reflection. MemberInfo
System. Reflection. EventInfo
System. Reflection. FieldInfo
System. Reflection. MethodBase
System. Reflection. ConstructorInfo
System. Reflection. MethodInfo
System. Reflection. PropertyInfo
System. Type
The usage of the above classes is as follows:
(1) Use Assembly to define and load the Assembly, load the module in the Assembly list, and locate the type in this Assembly and create instances of this type.
(2) Use the Module to understand the Assembly containing the Module and the classes in the Module, and obtain all global methods or other specific non-Global methods defined on the Module.
(3) Use ConstructorInfo to understand the name, parameters, access modifiers (such as pulic or private) and implementation details (such as abstract or virtual) of the ConstructorInfo. Use the GetConstructors or GetConstructor method of Type to call a specific constructor.
(4) use MethodInfo to understand the method name, return type, parameters, access modifiers (such as pulic or private), and implementation details (such as abstract or virtual. Use the GetMethods or GetMethod method of Type to call a specific method.
(5) Use FiedInfo to learn the field name, access modifier (such as public or private), implementation details (such as static), and obtain or set the field value.
(6) Use EventInfo to learn about the event name, event handler data type, custom attributes, declaration type, and reflection type, and add or remove event handlers.
(7) Use PropertyInfo to understand the attribute name, data type, declaration type, reflection type, read-only or writable status, and obtain or set the attribute value.
(8) Use ParameterInfo to know the parameter name, data type, input parameter, output parameter, and the parameter location in the method signature.

When you work in only reflection context of an application domain, use CustomAttributeData to learn about custom attributes. With CustomAttributeData, you do not have to create Attribute instances to check them.
The System. Reflection. Emit namespace class provides a special form of Reflection that enables you to generate types at runtime.
Reflection can also be used to create an application called a type browser. It allows you to select a type and view information about the selected type.
Reflection has other functions. JScript and other language compilers use reflection to construct symbol tables. The classes in the System. Runtime. Serialization namespace use reflection to access data and determine the fields to be permanently saved. Classes in the System. Runtime. Remoting namespace indirectly use Reflection Through serialization.


Layered reflection model:


 
(Note: There is a one-to-many relationship between layers)

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 specially used for the development and use of clr development compilers, so you must realize that not all reflection types are suitable for everyone.

Example:

App. config configuration file information

<Configuration>
<Deleetask>
<Add key = "DBHeper" value = "Adapter. SQLHelper"/>
<! -- <Add key = "DBHeper" value = "Adapter. OracleHelper"/> -->
</AppSettings>
</Configuration>

 

Calls in the program

Private IDBHelper DbHelper = GetDBHelper ();
Public static IDBHelper GetDBHelper ()
{
String strClass = ConfigurationSettings. etettings ["DBHeper"]. ToString ();
Assembly assembly = Assembly. Load ("Adapter ");
IDBHelper dbHelper = assembly. CreateInstance (strClass) as IDBHelper;
Return dbHelper;
}

 

You can select the SQL database or Oracle database through the configuration file.

 

 

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 strongly recommended method. The Load method carries an Assembly flag and loads it. Load will cause the CLR to apply the policy to the Assembly, 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 load method of AppDomain whenever possible.

Differences between Assembly. LoadFrom () and Assembly. Load ()

Application of Assembly. LoadFrom:

App. config configuration file information

<Assembly name = "SMSSender" ThreadCount = "1" class = "SMSSender. LDKSMSSender" path = "SMSSender. dll">
</Assembly> call in the program

Assembly assembly = Assembly. LoadFrom (Server. MapPath (assemblyPath ));
ISaaSProcess proc = assembly. CreateInstance (assemblyObj. Class) as ISaaSProcess;

 

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.
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.

 

Use reflection to create an instance of the type:

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 msdn.
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 createappsacefromanunwrap
4. InvokeMember instance method of System. type: This method returns a constructor that matches the input parameter and constructs this type.
5. Invoke instance method of System. reflection. constructinfo

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.
2. Implemented through interfaces. At runtime,

Related 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.