C # Reflection mechanism

Source: Internet
Author: User
Tags modifiers

Reflection Definition: the ability to review metadata and collect type information about it. Metadata (the most basic data unit after compilation) is a whole bunch of tables, and when the assembly or module is compiled, the compiler creates a class definition table, a field definition table, and a method definition table.

The common language runtime (CLR) loader manages application domains, which form a defining boundary around objects that have the same application scope. This management includes loading each assembly into the appropriate application domain and controlling the memory layout of the type hierarchy in each assembly.
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
Here are some of the ways to use the above classes:
(1) Use assembly to define and load assemblies, load list modules in an assembly manifest, and find types from this assembly and create instances of that type.
(2) Use the module to understand the assemblies that contain modules, the classes in modules, and so on, and to get all global methods or other specific non-global methods defined on the module.
(3) Use ConstructorInfo to understand the name of the constructor, arguments, access modifiers (such as pulic or private), and implementation details (such as abstract or virtual). Use the GetConstructors or GetConstructor method of type to invoke a specific constructor.
(4) Use MethodInfo to understand the name of the method, the 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 invoke a specific method.
(5) Use Fiedinfo to understand the name of a field, access modifiers (such as public or private) and implementation details (such as static), and get or set field values.
(6) Add or remove event handlers by using EventInfo to understand the name of the event, the event handler data type, the custom attribute, the claim type, and the reflection type.
(7) Use PropertyInfo to understand the name, data type, claim type, reflection type, and read-only or writable state of the property, and to get or set the property value.
(8) Use ParameterInfo to understand the name of the parameter, the data type, whether it is an input parameter or an output parameter, and the position of the parameter in the method signature.

When you are working in the reflection-only context of an application domain, use CustomAttributeData to learn about custom properties. With CustomAttributeData, you can examine them without having to create an instance of the property.
The class of the System.Reflection.Emit namespace provides a special form of reflection that enables you to generate types at run time.
Reflection can also be used to create an application called a type browser, which enables the user to select a type and then view information about the selected type.
There are some other uses for reflection. Language compilers such as JScript use reflection to construct symbol tables. Classes in the System.Runtime.Serialization namespace use reflection to access data and determine which fields to persist. The classes in the System.Runtime.Remoting namespace use reflection indirectly through serialization.


Hierarchical model of Reflection:

(Note: Hierarchy is a one-to-many relationship)

The effect of reflection:
1. You can use reflection to dynamically create instances of types, bind types to existing objects, or get types from existing objects
2. Applications need to load a specific type from a particular assembly at run time so that reflection can be used when a task is implemented.
3, reflection of the main application and class library, these class libraries need to know a type of definition, in order to provide more functionality.

Application Highlights:
1. Few applications in real-world applications need to use reflection types
2. Dynamic binding with reflection requires sacrificing performance
3. Some metadata information is not available through reflection
4. Some reflection types are used specifically for development of CLR development compilers, so you should realize that not all reflection types are suitable for everyone.

Example:

App. Config profile information

123456 <configuration> &NBSP;&NBSP; <APPSETTINGS> Code class= "CSharp spaces" >&NBSP;&NBSP;&NBSP;&NBSP; <add key= "Dbheper"  value= "Adapter.sqlhelper" /> &NBSP;&NBSP;&NBSP; <!--<add key= "Dbheper"  value= "Adapter.oraclehelper" />--> &NBSP;&NBSP; </APPSETTINGS> </CONFIGURATION>

Calls in the program

12345678 privateIDBHelper DbHelper = GetDBHelper();publicstaticIDBHelper GetDBHelper(){    stringstrClass = ConfigurationSettings.AppSettings["DBHeper"].ToString();    Assembly assembly =  Assembly.Load("Adapter");    IDBHelper dbHelper = assembly.CreateInstance(strClass) asIDBHelper;    returndbHelper;}

The configuration file allows you to select whether the system selects a SQL database or an Oracle database.

To reflect a single assembly:

The above approach is about reflecting all the assemblies of the AppDomain, and we can show the call to one of the assemblies, the system.reflecton.assembly type provides the following three ways:
1, Load method: A highly recommended method, the Load method with an assembly flag and load it, load will cause the CLR to apply the policy to the Assembly, successively in the global assembly buffer, the application base directory and the private path below the assembly, if it cannot find the assembly system throws an exception
2, LoadFrom method: Pass the path name of an assembly file (including the extension), the CLR will load the assembly you specify, pass this parameter cannot contain any information about the version number, culture, and public key information, if the specified path cannot find the assembly throws an exception.
3. LoadWithPartialName: Never use this method because the application cannot determine the version of the assembly that is being loaded again. The only use of the method is to help those in the. NET Framework to test the client using the. NET Framework to provide some kind of behavior, this method will eventually be discarded.

Note: System. The AppDomain also provides a load method, unlike the static Load method of assembly, the AppDomain's Load method is an instance method that returns a reference to the assembly, assembly static load Imagining sends an assembly in a value wrapper back to the AppDomain that made the call. Try to avoid using the AppDomain's Load method.

The difference between Assembly.LoadFrom () and Assembly.Load ()

Application of Assembly.LoadFrom ():

App. Config profile information

12 <assembly name="SMSSender"ThreadCount="1" class="SMSSender.LDKSMSSender"path="SMSSender.dll"></assembly>
1  
1  

Calls in the program

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

Load method: A highly recommended method, load method with an assembly flag and load it, load will cause the CLR to apply the policy to the Assembly, in the global assembly buffer, the application base directory and the private path to find the assembly, if it cannot find the assembly system throws an exception
LoadFrom method: Pass the path name of an assembly file (including the extension), the CLR will load the assembly that you specify, the parameter passed cannot contain any information about the version number, culture, and public key information if the assembly is not found in the specified path to throw an exception.

To create an instance of a type by reflection:

By reflection, you can get the type of the assembly, and we can create a new instance of that type based on the type of assembly that was obtained, which is also the feature of late binding to create an object at run time, as mentioned earlier
We can do this in several ways:
1, the CreateInstance method of System.activator. The method returns a reference to the new object. See MSDN for details on how to use it
2. The createinstancefrom of System.activator is similar to the previous method, but requires specifying the type and its assembly
3, System.AppDomain method: Createinstance,createinstanceandunwrap,createinstrancefrom and Createinstracefromandunwrap
4. InvokeMember instance method for System.Type: This method returns a constructor that matches the incoming parameter and constructs the type.
5. System.reflection.constructinfo Invoke Instance method

Interface of the Reflection type:

If you want to get a collection of all the interfaces inherited by a type, you can call the type findinterfaces getinterface or getinterfaces. All of these methods can only return interfaces that are directly inherited by that type, and they do not return interfaces inherited from an interface. The underlying interface to return the interface must call the above method again.

Performance of Reflection:

Using reflection to invoke a type or trigger method, or to access a field or property, the CLR needs to do more: Verify the parameters, check permissions, and so on, so the speed is very slow. So try not to use reflection for programming, for applications that intend to write a dynamically constructed type (late binding), you can do this in one of several ways:
1, through the inheritance relationship of the class. Let the type derive from a compile-time-aware underlying type, generate an instance of the type at run time, place a reference to it in a variable of its underlying type, and then invoke the virtual method of the underlying type.
2, through the interface implementation. At run time, build an instance of the type, place a reference to it into a variable of its interface type, and then invoke the virtual method defined by the interface.
3, through the implementation of the Commission. Let the type implement a method whose name and prototype match a delegate that is known at compile time. Constructs an instance of the type at run time, then constructs an instance of the delegate with the object and name of the method, and then invokes the method you want through the delegate. This method is relatively less efficient than the previous two methods.

Reflection Example

1.

123 inti = 42;System.Type type = i.GetType();System.Console.WriteLine(type);

Output is: System.Int32

2.

12 System.Reflection.Assembly info = typeof(System.Int32).Assembly;System.Console.WriteLine(info);

Output: mscorlib, version=2.0.0.0, Culture=neutral, publickeytoken=b77a5c561934e089

System.Type

Most methods of System.Type are used to obtain member information for the corresponding data type: Constructors, properties, methods, events, and so on. It has many methods, but they all have the same pattern. For example, there are two ways to get method information for a data type: GetMethod () and GetMethods (). The GetMethod () method returns a reference to the System.Reflection.MethodInfo object that contains information about a method. GetMethods () returns an array of such references. The difference is that GetMethods () returns information for all methods, while GetMethod () returns information about a method that contains a specific list of parameters. Both methods have overloaded methods, which have an additional parameter, BindingFlags enumeration values, that indicate which members should be returned, such as returning public members, instance members, and static members.

1 示例:
1234567891011121314151617 /// <summary>/// 运行所有方法/// </summary>publicvoidRunMethods(){    stringstrClass = ConfigurationSettings.AppSettings["DBHeper"].ToString();    Assembly assembly = Assembly.Load("Adapter");    Type[] types = assembly.GetTypes();    foreach(Type type intypes)    {        MethodInfo[] methods = type.GetMethods();        foreach (MethodInfo method inmethods)        {            method.Invoke(null, null);        }    }}

C # Reflection mechanism

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.