Reflection learning 1-C # 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. Program 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 tables Code

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

 

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 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 appdomain load method whenever possible

Use reflection to obtain the type information:

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 (); // defines a new class.
// Call a reflecting.exe assembly

Assembly myassembly assembly.loadfrom(“reflecting.exe ")
Reflect. getreflectioninfo (myassembly); // gets the reflection Information
}

// define a method for obtaining reflection content
void getreflectioninfo (Assembly myassembly)
{< br> type [] typearr = myassemby. gettypes (); // obtain the type
foreach (type in typearr) // obtain detailed information for each type
{< br> // obtain the structure information of the type
constructorinfo [] myconstructors = type. getconstructors;

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

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

// Obtain the 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 the 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
}

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

 

Personal operation plan:

Source DLL class:

Using system;
Using system. Collections. Generic;
Using system. text;
Using system. Text. regularexpressions;
Using system. Web. UI;
Using system. collections;

Namespace CN. swordyang
{

Public class textclass: system. Web. UI. Page
{

Public static void runjs (page _ page, string source)
{
_ Page. clientscript. registerstartupscript (_ page. getType (), "", "<SCRIPT type = \" text/JavaScript \ ">" + Source + "; </SCRIPT> ");

}

}

}

 

// Call the code

System. reflection. Assembly ass = assembly. loadfrom (server. mappath ("bin/swordyang. dll"); // load DLL
System. type T = ass. GetType ("cn. swordyang. textclass"); // obtain the type
Object o = system. activator. createinstance (t); // create an instance

System. reflection. methodinfo MI = T. getmethod ("runjs"); // obtain the Method

Mi. Invoke (O, new object [] {This. Page, "alert ('test reflection method')"}); // CALL THE METHOD

 

 

Reflection mechanisms correspond to policy modes in Design Patterns

 

Reprinted from: http://hi.baidu.com/wuzj/blog/item/ca4a848bcedafcd4fc1f1018.html

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.