C # functions and key points of reflection technology,

Source: Internet
Author: User

C # functions and key points of reflection technology,

Reflection (Reflection) is. NET, which can be obtained at runtime through radiation. NET, including methods, attributes, events, and constructor. You can also obtain the name, qualifier, and parameters of each member. With reflection, you can be familiar with every type. If you obtain information about the constructor, you can directly create an object, even if the object type is unknown during compilation.

1.. NET executable application structure

The program code is compiled to generate an executable application. First, we need to understand the structure of this executable application.

The application structure can be divided into application domain-assembly-module-type-member layers, and the common language runtime loader manages the application domain, such management includes loading each assembly to the corresponding application domain and controlling the memory layout of the type hierarchy of each set.

The Assembly contains modules, while the module contains types and types, and reflection provides encapsulated assembly, module, and type objects. We can use reflection to dynamically create instances of the type, bind the type to an existing object or obtain the type from the existing object, and then call the method of the type or access its fields and attributes. Reflection is usually used for the following purposes.

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

The System. Reflection. Emit namespace class provides a special form of Reflection that can be constructed at runtime.

Reflection can also be used to create an application called a type browser, allowing you to select a type and view information about the selected type.

In addition, Jscript and other language compilers use reflection to construct symbol tables. 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 use reflection indirectly through Serialization.

Using System;
Using System. Reflection;

Namespace ReflectionExample
{
Class Class1
{
[STAThread]
Static void Main (string [] args)
{
System. Console. WriteLine ("list all types in the assembly ");
Assembly a = Assembly. LoadFrom ("ReflectionExample.exe ");

Type [] mytypes = a. GetTypes ();

Foreach (Type t in mytypes)
{
System. Console. WriteLine (t. Name );
}
System. Console. ReadLine ();

System. Console. WriteLine ("list all methods in HelloWorld ");

Type ht = typeof (HelloWorld );

MethodInfo [] mif = ht. GetMethods ();

Foreach (MethodInfo mf in mif)
{
System. Console. WriteLine (mf. Name );
}

System. Console. ReadLine ();

System. Console. WriteLine ("instantiate HelloWorld and call SayHello method ");

Object obj = Activator. CreateInstance (ht );

String [] s = {"ZhenLei "};

Object objName = Activator. CreateInstance (ht, s );

// BindingFlags flags = (BindingFlags. NonPublic | BindingFlags. Public |
// BindingFlags. Static | BindingFlags. Instance | BindingFlags. DeclaredOnly );

MethodInfo msayhello = ht. GetMethod ("SayHello ");

Msayhello. Invoke (obj, null );

Msayhello. Invoke (objName, null );

System. Console. ReadLine ();


}


}
}

Using System;

Namespace ReflectionExample
{
/// <Summary>
/// Summary of HelloWorld.
/// </Summary>
Public class HelloWorld
{
String myName = null;

Public HelloWorld (string name)
{
MyName = name;
}
Public HelloWorld (): this (null)
{

}

Public string Name
{
Get
{Return myName ;}
}

Public void SayHello ()
{
If (myName = null)
System. Console. WriteLine ("Hello World ");
Else
System. Console. WriteLine ("Hello," + myName );
}

}
}
3. Use reflection technology in design mode implementation

Reflection technology can simplify factory implementation.

(1) Factory method: The subclass name to be implemented can be passed to the factory method through reflection, so that class instantiation is not required in the subclass.

(2) Abstract Factory: Using Reflection can reduce subclass of abstract factory.

Using Reflection technology can simplify the complexity of Factory Code. In the. NET project, factories using reflection technology have basically replaced the factory method.

The reflection technology can greatly simplify the generation of objects and greatly affect the implementation of the following design patterns.

(1) command mode: You can use the command type name as a parameter to directly obtain the command instance and dynamically execute the command.

(2) metadata sharing mode: Using Reflection technology to instantiate the metadata sharing mode can simplify the metadata sharing factory.
4.

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. When compiling an assembly or module, the compiler creates a class definition table and a field definition table, and a method definition table ,. The System. reflection namespace contains several classes that allow you to reflect (PARSE) the Code of these metadata tables
Reflection-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

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 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 ())
{
// Reflect the information of 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:

1 using system; 2 using sytem. reflection; 3 class reflecting 4 {5 static void Main (string [] args) 6 {7 reflecting reflect = new reflecting (); // define a new class 8 // call a reflecting.exe assembly 9 assembly myAssembly implements assembly.loadfrom(“reflecting.exe ") 10 reflect. getreflectioninfo (myAssembly); // obtain reflection information 11} 12 // define a method for obtaining reflection content 13 void getreflectioninfo (assembly myassembly) 14 {15 type [] typearr = myassemby. gettypes (); // obtain the type 16 foreach (type in typearr) // obtain the detailed information for each type 17 {18 // obtain the type structure information http://www.cnblogs.com/sosoft/19 Constructorinfo [] myconstructors = type. getConstructors; 20 // obtain the type of field information 21 fieldinfo [] myfields = type. getFiedls () 22 // obtain method information 23 MethodInfo myMethodInfo = type. getMethods (); 24 // get Property Information 25 propertyInfo [] myproperties = type. getProperties 26 // get event information 27 EventInfo [] Myevents = type. getEvents; 28} 29} 30}

 



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
Http://www.cnblogs.com/sosoft/
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. This type is derived from a known basic type during compilation. An instance of this type is generated at runtime, and its reference is placed in a variable of its basic type, then, call the virtual method of the basic type.

2. Implemented through interfaces. At runtime, construct an instance of this type, place its reference to a variable of its interface type, and then call the virtual method defined by this interface.

3. implement it through delegation. Let this type implement a method. Its name and prototype are consistent with a delegate that is known during compilation. Construct an instance of this type at runtime, then construct the instance of the delegate using the object and name of the method, and then call the method you want through the delegate. This method is more efficient than the previous two methods.

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.