Reflection in. NET (reprint)

Source: Internet
Author: User
Tags modifiers

Original address: http://www.cnblogs.com/Stephenchao/p/4481995.html

Two real-world examples:
1, B Super: Everyone has done a physical examination of the B-Super bar, B-ultrasound can be detected through the belly of your internal organs of the physiological situation. How is this done? B-Ultrasound is a B-type ultrasonic, it can through the belly through to your body to launch B-type ultrasound, when the ultrasonic wave encountered internal organs will produce a certain "echo" reflection, and then the "echo" to deal with the situation can show the internal organs (I am not a doctor is not an acoustic expert, I do not know whether accurate ^_^).
2, the internal structure of the Earth: the internal structure of the earth can be divided into three layers: the crust, mantle and core. The crust is solid, the core is liquid, the mantle is semi-liquid semi-solid structure (middle school geography content, you remember?) )。 How do you know the inner structure of the earth without going deep inside the earth? Yes, to the Earth to launch "seismic wave", "seismic wave" divided into two kinds is "transverse wave", the other is "longitudinal wave". "Shear wave" can only penetrate the solid, and "longitudinal" can penetrate the solid and can penetrate the liquid. By the inversion of the longitudinal and transverse waves on the ground, we can roughly determine the structure of the Earth's interior.

It is noted that the common feature of these two examples is to understand the inner structure of an object from the outside of an object, and to take advantage of the reflection function of the wave. Reflection in. NET also enables the ability to understand the internal structure of an object (or assembly) from the outside of an object, even if you don't know what the object (or assembly) is, in addition. NET can also be used to create an object and execute its methods.

Reflection is. NET, through reflection, you can get information about the members and members of each type (including classes, structs, delegates, interfaces, enumerations, and so on) in a program or assembly at run time. With reflection, you can get a sense of each type. In addition, I can create objects directly, even if the type of the object is not known at compile time.

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

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

main classes used for reflection:
System.Type Class-This class provides access to information for any given data type.
System.Reflection.Assembly class-It can be used to access information for a given assembly, or to load the assembly into a program.

System.Type class:
The System.Type class plays a central role in reflection. But it is an abstract base class, type has a derived class corresponding to each data type, we use the method, field, property of the object of this derived class to find all information about that type.
There are 3 common ways to get type references for a given type:
Use the C # typeof operator.
Type t = typeof (String);
Use the object GetType () method.
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 are to get the type string, after the string type of the reference T, we can use T to probe 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);
}

the properties of the type class:
Name Data type name
FullName fully qualified name of the data type (including namespace name)
Namespace defines the namespace name of the data type
IsAbstract Indicates whether the type is abstract type
IsArray Indicates whether the type is an array
IsClass Indicates whether the type is a class
Isenum Indicates whether the type is an enumeration
Isinterface Indicates whether the type is an interface
IsPublic Indicates whether the type is public
IsSealed Indicates whether the type is a sealed class
Isvaluetype Indicates whether the type is a value type
method of the type class:
GetConstructor (), GetConstructors (): Returns the ConstructorInfo type, which is used to obtain information about the constructor of the class
GetEvent (), GetEvents (): Returns the EventInfo type, which is used to obtain information about the event of the class
GetField (), GetFields (): Returns the FieldInfo type, which is used to obtain information about the field (member variable) of the class
GetInterface (), getinterfaces (): Returns the Interfaceinfo type, which is used to obtain information about the interface implemented by the class
GetMember (), GetMembers (): Returns the MemberInfo type, which is used to obtain information about all members of the class
GetMethod (), GetMethods (): Returns the MethodInfo type, which is used to obtain information about the method of the class
GetProperty (), GetProperties (): Returns the PropertyInfo type that is used to obtain information about the properties of the class
These members can be called by invoking the InvokeMember () method of type, or by invoking the Invoke () method of MethodInfo, PropertyInfo, and other classes.

to view the construction methods in a class:
NEWCLASSW NC = new NEWCLASSW ();
Type t = NC. GetType ();
constructorinfo[] ci = t.getconstructors ();Get all constructors for a class
foreach (ConstructorInfo c in CI)//Traverse each constructor
{
parameterinfo[] ps = C.getparameters ();Take out all parameters for each constructor
foreach (parameterinfo Pi in PS)//Traverse and print all parameters of the constructor
{
Console.Write (pi. Parametertype.tostring () + "" +pi. Name+ ",");
}
Console.WriteLine ();
}

To dynamically generate an object with a constructor:
Type t = typeof (NEWCLASSW);
type[] pt = new TYPE[2];
Pt[0] = typeof (String);
Pt[1] = typeof (String);
Get constructors based on parameter types
ConstructorInfo ci = t.getconstructor (PT);
Constructs an object array as an input parameter to the constructor
object[] obj = new object[2]{"Grayworm", "Hi.baidu.com/grayworm"};
Call the constructor to generate the object
object o = ci. Invoke (obj);
Call the method of the generated object to test whether the object was generated successfully
((NEWCLASSW) O). Show ();

To generate an object with activator:
Type t = typeof (NEWCLASSW);
Parameters of the constructor function
object[] obj = new Object[2] {"Grayworm", "Hi.baidu.com/grayworm"};
Generate new objects with Activator's CreateInstance static method
Object o = Activator.CreateInstance (t, "Grayworm", "Hi.baidu.com/grayworm");
((NEWCLASSW) O). Show ();

to view the properties in a class:
NEWCLASSW NC = new NEWCLASSW ();
Type t = NC. GetType ();
propertyinfo[] PiS = t.getproperties ();
foreach (PropertyInfo pi in PiS)
{
Console.WriteLine (pi. Name);
}

to view the public method in a 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 public fields in a class
NEWCLASSW NC = new NEWCLASSW ();
Type t = NC. GetType ();
fieldinfo[] fis = T.getfields ();
foreach (FieldInfo fi in FIS)
{
Console.WriteLine (FI. Name);
} (Http://hi.baidu.com/grayworm)

generate objects with reflection and invoke properties, methods, and fields to manipulate
NEWCLASSW NC = new NEWCLASSW ();
Type t = NC. GetType ();
Object obj = activator.createinstance (t);
Get ID field
FieldInfo fi = T.getfield ("ID");
Assigning a value to an ID field
Fi. SetValue (obj, "k001");
Get MyName Property
PropertyInfo pi1 = T.getproperty ("MyName");
Assigning a value to the MyName property
Pi1. SetValue (obj, "grayworm", null);
PropertyInfo pi2 = T.getproperty ("MyInfo");
Pi2. SetValue (obj, "hi.baidu.com/grayworm", null);
Get 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 information about an assembly, load an assembly dynamically, and find type information in an assembly, and create an instance of that type.
Using the Assembly class can reduce the coupling between assemblies and facilitate the rationalization of the software structure.

To return a assembly object by assembly name
Assembly-Assembly.Load ("ClassLibrary831");
Return assembly object by DLL file name
Assembly-Assembly.LoadFrom ("ClassLibrary831.dll");
To get an assembly class from assembly
Type t =.   GetType ("Classlibrary831.newclass"); Parameter must be the full name of the class
To get all the classes in the Assembly through Assembly
type[] t =. GetTypes ();

Reflection through the name of the Assembly
 Assembly-Assembly.Load ("ClassLibrary831");
Type t =. GetType ("Classlibrary831.newclass");
Object o = Activator.CreateInstance (t, "Grayworm", "Http://hi.baidu.com/grayworm");
MethodInfo mi = T.getmethod ("show");
Oil Invoke (o, null);

//reflect all of the types in the DLL file's full name
Assembly Assembly = Assembly.LoadFrom ("Path to Xxx.dll");
type[] AA = A.gettypes ();

foreach (Type t in AA)
{
if (T.fullname = = "A.B.C")
{
Object o = activator.createinstance (t);
}
}

Reflection in. NET (reprint)

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.