Definition of Reflection: the ability to review metadata and collect type information about it, metadata (the edited basic data unit) is a large list of tables, the compiler creates a class definition table, a field definition table, a method definition table, and so on, The System.Reflection namespace contains several classes that allow you to reflect (parse) the code of these meta data
I. The role of Reflection:
Dynamically create an instance of a type, set the type state to an existing object, or get a type from an existing object
The application needs to load a specific type from a particular assembly at run time so that a task can be implemented with reflection
Reflection is primarily applied to class libraries, which need to know the definition of a type to provide more functionality
Second, the application points:
Reflection is rarely used in real-world applications
Using reflection dynamic bonding requires sacrificing performance
Some meta data information is not available through reflection
Some reflection types are specifically developed for use by those CLR development editors, so you want to mean that not all reflection types are available
Third, the method of obtaining assembly:
Assembly.Load
Assembly.loadfile
Assembly.LoadFrom
assembly method of type Object
Iv. reflected members:
Memberinfo-Members
Constructorinfo-structure
fieldinfo-Field
Methodinfo-method
Propertyinfo-Property
eventinfo-Events
=========================================================================
1. Type class
static void Main (string[] args)
{Myclass my = new Myclass ();
Type type = My. GetType (); object to get the type object of the class to which this object belongs
Console.WriteLine (type. Name); About class General: Class name, namespace, assembly
Console.WriteLine (type. Namespace);
Console.WriteLine (type. Assembly);
fieldinfo[] Array = type. GetFields (); About the inside of a class: getting characters
foreach (var temp in array)
{
Console.WriteLine (temp. Name);
}
propertyinfo[] Array = type. GetProperties ()//Get Properties
foreach (var temp in array)
{
Console.WriteLine (temp. Name);
}
methodinfo[] Array = type. GetMethods (); Get method
foreach (var temp in array)
{
Console.WriteLine (temp. Name);
}
Console.readkey ();
}
2. Get the current program's assembly assembly
static void Main (string[] args)
{Myclass my = new Myclass ();
Assembly Assem = My. GetType (). Assembly; Gets the assembly it is in by using the type object of the class instance object (method 1 that loads the assembly)
Console.WriteLine (Assem. FullName);
type[] Array = Assem. GetTypes (); Get all classes in the assembly (program and MyClass two here)
foreach (var temp in array)
{
Console.WriteLine (array);
}
Console.readkey ();
}
Appendix:
Methods 2:assembly Assem = Assembly.Load ("someassembly"); Loads an assembly based on the name of the assembly.
Find in local directory and global Assembly cache directory
Methods 3:assembly Assem = Assembly.LoadFrom (@ "C:\xx\SomeAssembly.dll"); The full path of the assembly
*************************************************************************************************************** ***************************************************
The principle is simple,. NET writes an assembly that contains two important parts: IL (intermediate language code) and metadata (metadata). Isn't there a lot of classes in the code we're writing, and the class has a lot of members, and in compiling the code, the metadata table records all of the class's information in the code (it's actually a data structure, organization class information). And the reflection process is just the opposite, it is to find the members of the class through the details of the class as recorded in the metadata, and to make it "resurrected" (since the information recorded in the metadata is sufficiently detailed that the IL code for that class can be found and exploited according to the information recorded in metadata).
The final contrast:
Meta-data formation: form the record information of class according to the specific content of the code;
Reflection: Find the required code based on the records of the metadata;
As for the example, it is convenient to use the type class: type T = typeof (System.String);
memberinfo[] mis = t.getmembers ();
foreach (MemberInfo mi in mis) {
Console.WriteLine (MI. MemberType + mi. Name);
//You will get all the information about the string class;
Related *********************************************************
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
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