The reflection of C # Learning

Source: Internet
Author: User
Tags modifiers
1. What is reflection:
Reflection, Chinese translation for reflection.
This is. NET to get run-time type information. NET application consists of several parts: ' Assembly (Assembly) ', ' module ', ' type ', and reflection provides a programmatic way for programmers to obtain information about these components during the program's run time.

Overview of Reflections

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 System.Reflection namespace contains several classes that allow you to reflect (parse) the code of these metadata tables.


2, the specific use of reflection:

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


3. Reflection-related namespaces:


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


4, reflection of the hierarchical model:



Note: Hierarchies are one-to-many relationships

The effect of reflection:

1. You can use reflection to dynamically create an instance of a type, bind a type to an existing object, or get a type from an existing object
2. An application needs 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 is primarily applied to class libraries, which need to know the definition of a type 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.

6, the actual application of reflection:

The assembly that reflects the AppDomain

static void Main
{
Calling all the assemblies of the AppDomain through Getassemblies
foreach (Assembly Assem in Appdomain.currentDomain.GetAssemblies ())
{
Reflect information about the current assembly
Reflector. reflectonassembly (Assem)
}
}

Description: Calling the Getassemblies method of an AppDomain object returns an array of System.Reflection.Assembly elements.

Reflection of a single assembly

We can show the invocation of one of the assemblies, the system.reflecton.assembly type provides the following three ways:

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

Get type information with reflection

An example of a simple use of reflection to obtain type information:

using System;
Using Sytem.reflection;
Class reflecting
{
static void Main (String[]args)
{
Reflecting reflect=new reflecting ();//define a new self-class
Calling a Reflecting.exe assembly
Assembly myassembly =assembly.loadfrom ("Reflecting.exe")
Reflect.getreflectioninfo (myassembly);//Get reflection information
}
Define a method to get reflected content
void Getreflectioninfo (Assembly myassembly)
{
Type[] Typearr=myassemby. GetTypes ();//Get type
foreach (type type in Typearr)//Get more information for each type
{
Get structure information for a type
Constructorinfo[] Myconstructors=type. GetConstructors;
Get field information for a type
Fieldinfo[] Myfields=type. Getfiedls ()
Get method information
MethodInfo Mymethodinfo=type. GetMethods ();
Get Property Information
Propertyinfo[] Myproperties=type. GetProperties
Get event Information
Eventinfo[] Myevents=type. GetEvents;
}
}
}

Several other ways to get a type object:

1. The System.Type parameter is a string type that must specify the full name of the type (including its namespace)
2. System.Type provides two instances of the method: Getnestedtype,getnestedtypes
3. The instance method provided by the Syetem.Reflection.Assembly type is: gettype,gettypes,getexporedtypes
4. System.Reflection.Moudle provides these instance methods: Gettype,gettypes,findtypes

Set a member of a reflection type

The member of the reflection type is the bottom layer of data in the reflection hierarchy model. We can get a member of type through the GetMembers method of the Type object. If we are using a getmembers with no parameters, it returns only the public-defined static variables and instance members of that type, we can also return the specified type member by using the parameter's getmembers with the argument setting. The specific parameters refer to the detailed description of the System.reflection.bindingflags enumeration type in MSDN.

For example:

Set the member content of the type that needs to be returned
BindingFlags bf=bingdingflags.declaredonly|bingdingflags.nonpublic| Bingdingflags.public;
foreach (MemberInfo mi int t.getmembers (BF))
{
WriteLine (mi.membertype)//outputs the specified type member
}

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.
2. The createinstancefrom of System.activator is similar to the previous method, but the type and its assembly need to be specified.
3. Methods of System.AppDomain: Createinstance,createinstanceandunwrap,createinstrancefrom and Createinstracefromandunwrap
4. System.Type InvokeMember Instance method: This method returns a constructor that matches the incoming parameter and constructs the type.
5. Invoke instance method for System.reflection.constructinfo

interface of 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

The CLR does more work when it reflects: checking the parameters, inspecting permissions, and so on, the speed is very slow. Try not to program with reflection, for applications that intend to write a dynamically constructed type (late binding) can be substituted in the following ways:

1. The inheritance relationship through 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. Implemented through an interface. 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. Implemented by a delegate. 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.

Precautions for use:

1. Reflection Across Assemblies

In development, this is often the case where the types in the A.dll need to be reflected in the B.dll, and a run-time error is generated if you are not careful. For reflection across assemblies, remember two points:
(1) If you use TypeOf, the compilation can pass, then the reflection across the assembly will work correctly. It can be said that TypeOf is strongly type-supported. Like what

Type Suptype = typeof (EnterpriseServerBase.DataAccess.IDBAccesser);

If the current assembly does not add a reference to EnterpriseServerBase.dll, the compilation will error.

(2) If you use Type.GetType, the situation is more complicated, because Type.GetType is non-strongly typed. The Type.GetType parameter is a string, and when the string represents a target type that is not in the current assembly, the runtime Type.GetType returns NULL. The workaround is to load the target assembly first and then use the Assembly.GetType method. Such as

Assembly ASMB = Assembly.LoadFrom ("EnterpriseServerBase.dll");
Type Suptype = asmb. GetType ("EnterpriseServerBase.DataAccess.IDBAccesser");

Note that when using Type.GetType, even if you add a reference to EnterpriseServerBase.dll, Type.GetType (" EnterpriseServerBase.DataAccess.IDBAccesser ") also returns NULL, because Type.GetType only type searches in the current assembly.

2, reflection when the return type of a method is void

Type servicetype = typeof (T);
MethodInfo MethodInfo = Servicetype.getmethod (methodName);
Determines whether methodinfo.returntype = = typeof (void) is true.

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