Introduction to. Net reflection mechanism

Source: Internet
Author: User
Tags mscorlib

. Net reflection definition: ability to review metadata and collect information about its type.

Metadata is a binary information used to describe a portable executable file (PE) file stored in a Common Language Runtime library or a program stored in memory. When your code is compiled into a PE file, the metadata is inserted into a part of the file.

Convert the code to Microsoft intermediate language (msil) and insert it into another part of the file. Each type and member defined and referenced in a module or assembly is described in metadata.

When the code is executed, the runtime loads the metadata into the memory and references it to find information about the code, such as the class, member, and inheritance.

Metadata describes each type and member defined in the Code in a non-specific language. Metadata stores the following information:

Assembly description:

1. ID (name, version, region, public key ).

2. Export type.

3. Other Assembly on which the Assembly depends.

4. security permissions required for running.

Type description:

1. Name, visibility, base class, and implemented interface.

2. Members (methods, fields, attributes, events, and nested types ).

Attribute:

1. modify other descriptive elements of types and members.

The system. Reflection namespace contains several classes that allow you to reflect (PARSE) the code and reflection-related namespaces of these metabases (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

. Net 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. Reflection is often used when. Net implements the factory model. Many factory models are used.

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.

Reflection of a single assembly

1. Load Method: a highly recommended method. The load method carries an Assembly flag and loads it. Load will cause CLR to apply the policy to the Assembly.

Find the assembly in the global assembly Buffer, 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.

Layered Reflection Model

 

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

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

 

Http://www.fengfly.com/plus/view-81531-3.html

 

Another article

1. What is reflection?
Reflection, which is translated into reflection in Chinese.
This is.. net ,. NET applications are composed of several parts: 'assembly ', 'module', and 'Type (class) '. Reflection provides a programming method, this allows programmers to obtain relevant information about these components during the running period, for example:
The Assembly class can obtain information about running accessories, dynamically load the accessories, find the type information in the accessories, and create instances of this type.
The type class can obtain the type information of an object. This information includes all elements of the object, such as methods, constructors, and attributes. The type class can obtain and call the information of these elements.
Methodinfo contains information about the method. You can use this class to obtain the name, parameter, and return value of the method and call it.
For example, fieldinfo and eventinfo are included in the system. Reflection namespace.

2. Relationships between namespaces and accessories
Many people may not be clear about this concept. It is necessary to clarify this concept for qualified. Net programmers.
The namespace is similar to a Java package, but it is not exactly the same, because the Java package must be placed according to the directory structure, and the namespace is not required.

The assemblies are the units where the .netapp executes. All the compiled .dllw..exe files are accessories.

The relationship between accessories and namespaces is not one-to-one and does not contain each other. One Accessory can have multiple namespaces, and one namespace can also exist in multiple accessories, this may be a bit vague. For example:
Assembly:
Namespace N1
{
Public class AC1 {...}
Public class ac2 {...}
}
Namespace N2
{
Public class AC3 {...}
Public class ac4 {...}
}
Assembly B:
Namespace N1
{
Public class BC1 {...}
Public class BC2 {...}
}
Namespace N2
{
Public class bc3 {...}
Public class bc4 {...}
}

Both of the accessories have two namespaces, N1 and N2, and each declares two classes. This is completely acceptable. Then we reference assembly a in an application, in this application, we can see that the classes below N1 are AC1 and ac2, And the classes below N2 are Ac3 and ac4.
Then we remove the reference to a and add the reference to B, then the classes under N1 that we can see in this application become BC1 and BC2, and the same is true under N2.
If we reference these two accessories at the same time, we can see the following four classes in N1: AC1, ac2, BC1, and BC2.

Here, we can clearly understand a concept. The namespace only indicates the type of the family, such as the Han nationality and Hui nationality, and the accessories indicate the type of the family, for example, if someone lives in Beijing or Shanghai, then there are Han people in Beijing, Hui people in Shanghai, Han people in Shanghai, and Hui people. This is not a conflict.

As we have mentioned above, accessories are a place where the types reside. To use a class in a program, you must tell the compiler where the class lives before the compiler can find it, that is to say, the accessory must be referenced.
So when you write a program, you may not be sure where the class is, but you only know its name, can you use it? The answer is yes. This is reflection, that is, to provide this type of Address while the program is running, and find it.
If you are interested, let's take a look.

3. What is the purpose of obtaining type information during runtime?
Some people may wonder why the code can be written during development and is still executed at runtime, which is not only tedious but also inefficient.
This is a matter of opinion, just like early binding and late binding. Some people are opposed to late binding on the grounds of waste efficiency, but many people do not realize that they have used late binding when enjoying the benefits of virtual functions. This question is open. It's not clear in just a few words, so it's just a few minutes.
In my opinion, late binding can bring a lot of convenience in design. Proper use can greatly improve the reusability and flexibility of the program, but everything has two sides, it must be measured over and over again.

Next, what is the purpose of obtaining the type information during the runtime?
For example, many software developers prefer to leave some interfaces in their own software. Others can write some plug-ins to expand software functions. For example, I have a media player, I hope that the format of recognition can be easily extended in the future, so I declare an interface:
Public interface imediaformat
{
String extension {Get ;}
Decoder getdecoder ();
}
This interface contains an extension attribute, which returns a supported extension, and another method returns a decoder object (here I assume a decoder class, this class provides the function of decoding the file stream, which can be derived from the extension plug-in). I can interpret the file stream through the decoder object.
In this case, all decoding plug-ins must derive a decoder and implement this interface. In the getdecoder method, return the decoder object and configure its type name to my configuration file.
In this way, I do not need to know the type of the extended format when developing the player. I only need to obtain the type names of all decoder types from the configuration file, the dynamic creation of media format objects is used to convert them to the imediaformat interface.

This is a typical application of reflection.
4. How to Use reflection to obtain the type
First, let's look at how to obtain the type information.
There are two methods to obtain the type information. One is to obtain the instance object.
At this time, I only get this instance object. The method may be an object reference or an interface reference, but I don't know its exact type. I need to know, then you can call system. the GetType method declared on the object to obtain the type object of the Instance Object. For example, in a method, I need to determine whether the passed parameter has implemented an interface. If yes, then, a method of this interface is called:
...
Public void process (Object processobj)
{
Type T = processsobj. GetType ();
If (T. getinterface ("itest ")! = NULL)
...
}
...
Another method to obtain the type is to use the type. GetType and assembly. GetType methods, such:
Type T = type. GetType ("system. String ");
Note that we have mentioned the relationship between namespaces and accessories. To find a class, you must specify its accessories, or call GetType on the obtained Assembly instance.
In this Assembly, only the type name can be written, and the other exception is mscorlib. DLL, the type declared in this Assembly can also omit the Assembly name (. by default, mscorlib is referenced during the compilation of net accessories. DLL, unless it is explicitly specified during compilation), for example:
System. String is declared in mscorlib. dll. The above type T = type. GetType ("system. String") is correct.
System. Data. datatable is declared in system. Data. dll, so:
Type. GetType ("system. Data. able") can only get null references.
Required:
Type T = type. GetType ("system. Data. able, system. Data, version = 1.0.3300.0, culture = neutral, publickeytoken = b77a5c561934e089 ");
In this way.

5. How to dynamically create objects based on types
System. activator provides methods to dynamically create objects based on types, such as creating a datatable:

Type T = type. GetType ("system. Data. able, system. Data, version = 1.0.3300.0, culture = neutral, publickeytoken = b77a5c561934e089 ");

Datatable table = (datatable) activator. createinstance (t );

Example 2: Create an object based on the parameter Constructor
Namespace testspace {
Public class testclass
{
Private string _ value;
Public testclass (string value ){
_ Value = value;
}
}
}
...
Type T = type. GetType ("testspace. testclass ");
Object [] constructparms = new object [] {"Hello"}; // constructor Parameter
Testclass OBJ = (testclass) activator. createinstance (T, constructparms );
...
Put the parameters in an object array in order.
6. How to obtain methods and dynamic call Methods
Namespace testspace
{
Public class testclass {
Private string _ value;
Public testclass (){
}
Public testclass (string value)

{
_ Value = value;
}

 

 

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.