Reflection in C #

Source: Internet
Author: User
Tags foreach define definition class definition implement instance method reflection
Directory

Overview of Reflection

Reflection AppDomain Assemblies

Reflect a single assembly

Retrieving type information with Reflection

Set a member of a reflection type

Creating an instance of a type by reflection

Interface for reflection type

Performance of Reflection

Overview of Reflection

Definition of Reflection: the ability to review metadata and collect type information about it. Metadata (the most basic data unit after compilation) is a bunch of tables, and when you compile an assembly or module, the compiler creates a class definition table, a field definition table, and a method definition table, and so on. The System.Reflection namespace contains several classes that allow you to reflect (parse) the code of these metadata tables

and reflection-related namespaces (we are accessing 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

Hierarchical model of Reflection:






















Note: There is a one-to-many relationship between the layers

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. The application needs to load a specific type from a particular assembly at run time so that reflection can be used to implement a task.

3. Reflection is primarily applied to class libraries, which need to know the definition of a type in order to provide more functionality.

Application Essentials:

1. Few applications in a real-world application need to use reflection types

2. Dynamic binding with reflection requires sacrificing performance

3. Some meta data information is not available through reflection

4. Some reflection types are used specifically for development of those CLR development compilers, so realize that not all reflection types are suitable for everyone.



Reflection AppDomain Assemblies

When you need to reflect all the assemblies contained in the AppDomain, the examples are as follows:
static void Main

{

Calling all assemblies of AppDomain through Getassemblies

foreach (Assembly Assem in Appdomain.currentDomain.GetAssemblies ())

{

Reflect information about the current assembly

Reflector. reflectonassembly (Assem)

}

}

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

Reflect a single assembly

The above method is about all the assemblies that reflect AppDomain, and we can display a call to one of them, and the system.reflecton.assembly type provides the following three methods:

1. Load method: A highly recommended method in which the Load method takes an assembly flag and loads it, and the load causes the CLR to apply the policy to the Assembly, sequentially locating the assembly in the global Assembly buffer, the application base directory, and the private path, if the assembly system throws an exception if it is not found

2. LoadFrom method: Passes the path name (including the extension) of an assembly file, the CLR loads the assembly you specified, and the passed parameter cannot contain any information about the version number, culture, and public key information, if the assembly throws an exception that is not found on the specified path.

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 this method is to help those in. NET Framework testing process using the. NET Framework provides a customer with some behavior, this method will eventually be discarded.

Note: System. AppDomain also provides a load method, which is not the same as the static Load method of assembly, AppDomain's Load method is an instance method that returns a reference to an assembly, assembly static load Way the assembly is sent back to the calling AppDomain by value. Try to avoid using the AppDomain load method



Retrieving type information with Reflection

I'm done talking about the reflection of the Assembly, here is the third level in the Reflection hierarchy model, type reflection

A simple example of using reflection to get type information:

using System;

Using Sytem.reflection;

Class reflecting

{

static void Main (String[]args)

{

Reflecting reflect=new reflecting ()//define a new self class

Call a Reflecting.exe assembly

Assembly myassembly =assembly.loadfrom ("Reflecting.exe")

Reflect.getreflectioninfo (myassembly);//Get reflection information

}

Define a method to get the reflected content

void Getreflectioninfo (Assembly myassembly)

{

Type[] Typearr=myassemby. GetTypes ()//Get type

foreach (type type in Typearr)//Get detailed information for each type

{

Getting the structure information of a type

Constructorinfo[] Myconstructors=type. GetConstructors;

Get field information for 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 the 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 instance methods: Getnestedtype,getnestedtypes

3. The Syetem.Reflection.Assembly type provides an instance method that is: Gettype,gettypes,getexporedtypes

4. System.Reflection.Moudle provides these instance methods: Gettype,gettypes,findtypes

Set a member of a reflection type

A member of a reflection type is the bottom layer of data in the reflection hierarchy model. We can get members of a type by using 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, and we can return the specified type member by using the parameter setting with the GetMembers with the parameter. 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)/output the specified type member

}

Creating an instance of a type by reflection

By reflection, you can get the type of an assembly, and we can create a new instance of that type based on the type of assembly we get, which is also the function of creating an object late binding at run time, as mentioned earlier

We can do this in the following ways:

1. The CreateInstance method of System.activator. This method returns a reference to the new object. Use the specific method see MSND

2. System.activator's createinstancefrom is similar to the previous method, but you need to specify the type and its assembly

3. System.AppDomain methods: Createinstance,createinstanceandunwrap,createinstrancefrom and Createinstracefromandunwrap

4. System.Type InvokeMember Instance method: This method returns a constructor that matches the incoming argument and constructs the type.

5. System.reflection.constructinfo method of Invoke instance

Interface for reflection type

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

Performance of Reflection:

Using reflection to invoke a type or trigger a method, or to access a field or property, the CLR needs to do more: Validate parameters, check permissions, and so on, so the speed is very slow. So try not to program with reflection, and for applications that intend to write a dynamic constructed type (late bound), you can do the following in a few ways:

1. Inheritance relationships through classes. Let the type derive from a compile-time known base 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 that underlying type.

2. Implemented through an interface. At run time, an instance of the type is constructed, the reference to it is placed in a variable of its interface type, and then the virtual method defined by the interface is invoked.

3. implemented through delegates. Let the type implement a method whose name and prototype match a known delegate at compile time. The instance of the type is constructed at run time, then an instance of the delegate is constructed with the object and name of the method, and then the method you want is invoked by the delegate. This method is a little more effective than the previous two methods, and less efficient


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.