ASP. NET reflection,

Source: Internet
Author: User

ASP. NET reflection,

Two examples in reality:
1. B-ultrasound: You probably have performed B-ultrasound during the health check. B-ultrasound can detect the physiological status of your internal organs through your belly. How is this done? B-ultrasound is a B-type ultrasound. It can transmit B-type ultrasound to your body through the belly. When the ultrasound encounters an internal wall, it will produce a certain amount of "Echo" reflection, then, the "Echo" can be used to display the internal organs (I am not a doctor or an acoustic expert, and I do not know whether it is accurate ).
2. Earth's internal structure: the Earth's internal structure can be roughly divided into three layers: the Earth's crust, the mantle and the Earth's core. The earth's crust is solid, the Earth's core is liquid, and the Earth's mantle is semi-liquid and semi-solid (the content of Middle School Geography, do you remember ?). On the earth's surface, how can we know its internal structure without going deep into the earth? Yes, the seismic waves are emitted to the earth. The seismic waves are divided into two types: shear waves and longitudinal waves ". The "shear wave" can only penetrate the solid, while the "Longitudinal Wave" can penetrate both the solid and the liquid. Through the reverse return of the longitudinal and transverse waves on the ground, we can roughly determine the structure of the Earth.

We have noticed that the common feature of these two examples is to understand the internal structure of an object from the outside of an object, and they all use the reflection function of the wave. In. NET reflection can also be used to understand the internal structure of an object (or assembly) from outside the object, even if you do not know what the object (or assembly) is. NET reflection can also create an object and execute its methods.

Reflection is. NET. through reflection, you can obtain information about members and members of every type (including class, structure, Delegate, interface, and enumeration) in a program or set at runtime. With reflection, you can be familiar with every type. In addition, I can directly create an object even if the object type is unknown during compilation.

Purpose of reflection:
(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.
(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.
(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.

Namespace used for reflection:
System. Reflection
System. Type
System. Reflection. Assembly

Main classes used for reflection:
System. Type class -- this class can be used to access information of any given data Type.
System. Reflection. Assembly class -- it can be used to access the information of a given Assembly or load the Assembly into the program.

System. Type class:
The System. Type class plays a core role in reflection. But it is an abstract base class. Type has a derived class corresponding to each data Type. We use the methods, fields, and attributes of the object of this derived class to find all information about this Type.
There are three common methods to obtain Type references of a given Type:
● Use the C # typeof operator.
Type t = typeof (string );
● Use the GetType () method of the object.
String s = "grayworm ";
Type t = s. GetType ();
● You can also call the static method GetType () of the Type class ().
Type t = Type. GetType ("System. String ");

The above three types of code obtain the Type of the string Type. After the Type of the string Type is referenced with t, we can use t to detect the structure of the string Type.
String n = "grayworm ";
Type t = n. GetType ();
Foreach (MemberInfo mi in t. GetMembers ())
{
Console. WriteLine ("{0} \ t {1}", mi. MemberType, mi. Name );
}

Type attributes:
Name Data Type Name
Full qualified name of FullName data type (including namespace name)
Namespace: Namespace name that defines the data type
IsAbstract indicates whether this type is an abstract type.
IsArray indicates whether this type is an array.
IsClass indicates whether this type is a class
IsEnum indicates whether this type is Enumeration
IsInterface indicates whether this type is an interface
IsPublic indicates whether this type is public
IsSealed indicates whether this type is a seal class
IsValueType indicates whether this type is a value type.
Type method:
GetConstructor (), GetConstructors (): returns the ConstructorInfo type, which is used to obtain information about the ConstructorInfo class.
GetEvent (), GetEvents (): returns the EventInfo type, used to obtain the event information of this class.
GetField (), GetFields (): returns the FieldInfo type, used to obtain information about the fields (member variables) of this class.
GetInterface (), GetInterfaces (): returns the InterfaceInfo type, used to obtain information about interfaces implemented by this class.
GetMember (), GetMembers (): returns the MemberInfo type, used to obtain information about all members of this class.
GetMethod (), GetMethods (): return the MethodInfo type, used to obtain information about the method of this class
GetProperty (), GetProperties (): returns the PropertyInfo type, which is used to obtain the property information of this class.
You can call these members by calling the InvokeMember () method of Type, or by calling the Invoke () method of MethodInfo, PropertyInfo and other classes.

View the constructor in the class:
NewClassw nc = new NewClassw ();
Type t = nc. GetType ();
ConstructorInfo [] ci = t. GetConstructors ();// Obtain all constructors of the class
Foreach (ConstructorInfo c in ci) // traverses each Constructor
{
ParameterInfo [] ps = c. GetParameters ();// Retrieve all parameters of each Constructor
Foreach (ParameterInfo pi in ps) // Print and traverse all parameters of the constructor.
{
Console. Write (pi. ParameterType. ToString () + "" + pi. Name + ",");
}
Console. WriteLine ();
}

Use constructors to dynamically generate objects:
Type t = typeof (NewClassw );
Type [] pt = new Type [2];
Pt [0] = typeof (string );
Pt [1] = typeof (string );
// Obtain the constructor Based on the parameter type
ConstructorInfo ci = t. GetConstructor (pt );
// Construct an Object array as the input parameter of the constructor.
Object [] obj = new object [2] {"loveitdoit", "http://hi.baidu.com/loveitdoit "};
// Call the constructor to generate an object
Object o = ci. Invoke (obj );
// Call the method of the generated object to test whether the object is successfully generated
// (NewClassw) o). show ();

Use Activator to generate objects:
Type t = typeof (NewClassw );
// Constructor Parameters
Object [] obj = new object [2] {"grayworm", "http://hi.baidu.com/loveitdoit "};
// Use the CreateInstance static method of Activator to generate a new object
Object o = Activator. CreateInstance (t, "loveitdoit", "http://hi.baidu.com/loveitdoit ");
// (NewClassw) o). show ();

View attributes in the class:
NewClassw nc = new NewClassw ();
Type t = nc. GetType ();
PropertyInfo [] pis = t. GetProperties ();
Foreach (PropertyInfo pi in pis)
{
Console. WriteLine (pi. Name );
}

View the public method in the class:
NewClassw nc = new NewClassw ();
Type t = nc. GetType ();
MethodInfo [] mis = t. GetMethods ();
Foreach (MethodInfo mi in mis)
{
Console. WriteLine (mi. ReturnType + "" + mi. Name );
}

View the public field in the class
NewClassw nc = new NewClassw ();
Type t = nc. GetType ();
FieldInfo [] FCM = t. GetFields ();
Foreach (FieldInfo fi in FCM)
{
Console. WriteLine (fi. Name );
} Http://hi.baidu.com/loveitdoit

Generate an object Using Reflection and call properties, methods, and fields for operations
NewClassw nc = new NewClassw ();
Type t = nc. GetType ();
Object obj = Activator. CreateInstance (t );
// Obtain the ID field
FieldInfo fi = t. GetField ("ID ");
// Assign a value to the ID field
Fi. SetValue (obj, "k001 ");
// Obtain the MyName attribute
PropertyInfo pi1 = t. GetProperty ("MyName ");
// Assign a value to the MyName attribute
Pi1.SetValue (obj, "grayworm", null );
PropertyInfo pi2 = t. GetProperty ("MyInfo ");
Pi2.SetValue (obj, "hi.baidu.com/grayworm", null );
// Obtain the show Method
MethodInfo mi = t. GetMethod ("show ");
// Call the show Method
Mi. Invoke (obj, null );

System. Reflection. Assembly class 
The Assembly class can obtain the Assembly information, dynamically load the Assembly, find the type information in the Assembly, and create instances of this type.
Using the Assembly class can reduce the coupling between the Assembly and facilitate the rationalization of the software structure.

Return Assembly object by Assembly name
Assembly ass = Assembly. Load ("ClassLibrary831 ");
Return Assembly object by DLL file name
Assembly ass = Assembly. LoadFrom ("ClassLibrary831.dll ");
Obtain classes in the Assembly through Assembly
Type t = ass. GetType ("ClassLibrary831.NewClass"); // The parameter must be the full name of the class.
Obtain all classes in the Assembly through Assembly
Type [] t = ass. GetTypes ();

// Reflected by the Assembly name
 Assembly ass = Assembly. Load ("ClassLibrary831 ");
Type t = ass. GetType ("ClassLibrary831.NewClass ");
Object o = Activator. CreateInstance (t, "loveitdoit", "http://hi.baidu.com/loveitdoit ");
MethodInfo mi = t. GetMethod ("show ");
Mi. Invoke (o, null );

// All types are reflected by the full name of the DLL file
 Assembly assembly = Assembly. LoadFrom ("xxx. dll path ");
Type [] aa = a. GetTypes ();

Foreach (Type t in aa)
{
If (t. FullName = "a. B. c ")
{
Object o = Activator. CreateInstance (t );
}
}

Add a copy of the code... (Reprinted ):

Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. Data;
Using System. Collections;
Using System. Reflection;

Namespace KycBaseModule
{
Public class KycFunction
{
Public KycFunction (){}
/// <Summary>
/// Converts IList to DataSet
/// </Summary>
/// <Param name = "ResList"> IList to be converted </param>
/// <Returns> converted DataSet </returns>
Public static DataSet ListToDataSet (IList ResList)
{
DataSet RDS = new DataSet ();
DataTable TempDT = new DataTable ();

// Traverse the IList structure and create the same DataTable
System. Reflection. PropertyInfo [] p = ResList [0]. GetType (). GetProperties ();
Foreach (System. Reflection. PropertyInfo pi in p)
{
TempDT. Columns. Add (pi. Name, System. Type. GetType (pi. PropertyType. ToString ()));
}

For (int I = 0; I <ResList. Count; I ++)
{
IList TempList = new ArrayList ();
// Write a record in IList to ArrayList
Foreach (System. Reflection. PropertyInfo pi in p)
{
Object oo = pi. GetValue (ResList [I], null );
TempList. Add (oo );
}

Object [] itm = new object [p. Length];
// Traverse ArrayList to put data into object []
For (int j = 0; j <TempList. Count; j ++)
{
Itm. SetValue (TempList [j], j );
}
// Add the object [] content to the DataTable
TempDT. LoadDataRow (itm, true );
}
// Put DateTable into DataSet
RDS. Tables. Add (TempDT );
// Return DataSet
Return RDS;
}
}
}

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.