C # Reflection detailed

Source: Internet
Author: User
Tags modifiers

Original link: https://www.cnblogs.com/Stephenchao/p/4481995.html reflection Definition

Reflection provides objects (type types) that encapsulate assemblies, modules, and types. 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 and call its methods or access its fields and properties. If you use attributes in your code, you can use reflection to access them. MSDN uses scenarios to access the attributes of program metadata. Examine and instantiate the types in the assembly. Build the new type at run time. Use the classes in System.Reflection.Emit. Performs late binding to access methods of types that are created at run time. "MSDN" image description

  the internal structure of the Earth: The internal structure of the earth can be roughly divided into three layers: the crust, the mantle and the core. The crust is a solid, the core is a liquid, and the mantle is a semi liquid semi-solid structure (geo-knowledge). How to know the inner structure of the earth without going deep into the Earth's surface? The answer is: "Earthquake waves" to the earth. Seismic waves are divided into two kinds, one is transverse wave and the other is longitudinal wave. Transverse waves can penetrate only solids, while longitudinal waves penetrate solids and penetrate liquids. By the return of longitudinal and transverse waves on the ground, we can generally determine the structure of the Earth's interior.

  B-Type ultrasound : Everyone has done a physical examination of B-Ultrasound bar, B-ultrasound can be detected through the belly of your internal organs physiological situation. This is how to do it. The answer is: it can launch through the belly of B-type ultrasound, when the ultrasound encountered visceral wall will produce a certain "echo" reflection, and then the "echo" to deal with can show the situation of your internal organs. (partial details are not investigated)

One of the common features of these two examples is to understand the inner structure of objects from the outside of an object, and to take advantage of the reflection function of the wave. Reflection in. NET can also implement the ability to understand the internal structure of an object (or assembly) from the outside of an object, even if you do not know what the object (or assembly) is, and otherwise. NET can also dynamically create an object and execute its methods.

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

(1) Use assembly to define and load assemblies, load all modules in an assembly, and find types from this assembly and create instances of that type.
(2) Use module to understand the assembly that contains the module and the classes in the module, and to obtain all the 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) of constructors, and implementation details such as abstract or virtual.
(4) Use MethodInfo to understand the name of the method, return type, parameter, access modifier (such as pulic or private), and implementation details such as abstract or virtual.
(5) Use Fiedinfo to understand the name of the field, access modifiers (such as public or private) and implementation details (such as static), and get or set the field value.
(6) Add or remove event handlers by using EventInfo to understand the name of the event, event handler data type, custom attribute, declaring type, and reflection type, and so on.
(7) Get or set the property value by using PropertyInfo to understand the name, data type, declaring type, reflection type, and read-only or writable state of the property.
(8) Use ParameterInfo to understand the name of the parameter, data type, input or output parameters, and the position of the parameter in the method signature. the namespace used by reflection

System.Reflection
System.Type
System.Reflection.Assembly
main classes used for reflection
System.Type Class-This class allows you to access information for any given data type.
System.Reflection.Assembly Class--it can be used to access information about a given assembly, or to load the assembly into a program.
System.Type Class Usage

The System.Type class plays a central role in reflection. But it's an abstract base class, type has a derived class that corresponds to each data type, and we use the methods, fields, and properties of the object of this derived class to find all the information about that type. There are 3 common ways to get type references of the given types:

1. Using the C # typeof operator

Type t = typeof (String);

2, the use of object GetType () method

string s = "Grayworm";

3, can also call the type class static method GetType ()

Type t = Type.GetType ("System.String");
properties of type classThe name data type name FullName the fully qualified name of the data type (including the namespace name) Namespace the namespace name that defines the data type isabstract indicates whether the type is an 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 type classGetConstructor (), GetConstructors (): Returns the ConstructorInfo type that is used to obtain information about the constructor of the class GetEvent (), GetEvents (): Returns the EventInfo type, Information used to obtain the event for 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 GetMethod () for all members of the class, GetMethods ( ): Returns the MethodInfo type, which is used to obtain information about the method of the class GetProperty (), GetProperties (): Returns the PropertyInfo type, which is used to obtain information about the properties of the class

We can call these members by calling the InvokeMember () method of type, or by invoking the Invoke () method of the MethodInfo, PropertyInfo, and other classes. Instance Application

Instance class
Reflectionclass
{public
    int id;

    private string name;
    <summary>
    ///name
    ///</summary> public
    string name
    {Get
        {return name;}
        set {name = value;}
    }
    private string age;
    <summary>
    ///Age
    ///</summary> public
    string ages
    {get
        }
        set {age = value;}
    }
    private string sex;
    <summary>
    ///Sex
    ///</summary> public
    string Sex
    {get
        {return Sex;}
        set {sex = value;}
    }

    Public Reflectionclass (string name, String age)
    {
        this.name = name;
        This.age = age;
    }
    Public Reflectionclass (String sex)
    {
        this.sex = sex;
    }
    Public Reflectionclass ()
    {} public

    void Show ()
    {
        Console.WriteLine ("Name:" + name + "\ n" + "Age:" +) + "\ n" + "Sex:" + Sex);
    }

1. View the construction methods in the class

Reflectionclass rc = new Reflectionclass ();
Type t = RC. GetType ();
constructorinfo[] Ciarray = T.getconstructors (); Gets all constructors of the class
foreach (ConstructorInfo ci in ciarray)
{
    parameterinfo[] Piarray = ci. GetParameters (); Remove all parameters for each constructor,
    foreach (ParameterInfo pi in Piarray)
    {
        Console.WriteLine pi. Parametertype.tostring () + "\ n" +pi. Name+ "\ n");
    }

Print results:

Figure 1-1 Viewing the construction methods in a class
2. Dynamically generating objects with constructors

Type t = typeof (Reflectionclass);
Type[] pt = new TYPE[2];
Pt[0]=typeof (string);
Pt[1]=typeof (string);
Gets the constructor based on the parameter type
constructorinfo ci = t.getconstructor (PT);
Constructs an object array as the input parameter of the constructor
object[] obj = new Object[2] {"Zhangsan", "n"};
Call constructor to generate object
o = ci. Invoke (obj);
The method that invokes the generated object tests whether the object was generated successfully
((Reflectionclass) o). Show ();

Print results:

figure 1-2 dynamically generating objects with constructors
3. Generate objects with Activator

Type t = typeof (Reflectionclass);
object[] obj = new Object[2] {"Zhangsan", "n"};
A new object
o = activator.createinstance (t, obj) is generated using the Activator CreateInstance static method;
((Reflectionclass) o). Show ();

Print results:

Figure 1-3 Generating objects with activator
4, view the properties in the class

Reflectionclass rc = new Reflectionclass ();
Type t = RC. GetType ();
propertyinfo[] Piarray = T.getproperties ();
foreach (PropertyInfo pi in Piarray)
{
    Console.WriteLine (pi. Name);

Print results:

Figure 1-4 Viewing the properties in a class
5, view the public method in the class

Reflectionclass rc = new Reflectionclass ();
Type t = RC. GetType ();
methodinfo[] mi = t.getmethods ();
foreach (MethodInfo) (mi)
{
    Console.WriteLine (method). ReturnType + "\ n" + method. Name);

Print results:

Figure 1-5 Viewing the public method in a class
6, view the public fields in the class

Reflectionclass rc = new Reflectionclass ();
Type t = RC. GetType ();
Fieldinfo[] fi = T.getfields ();
foreach (FieldInfo fieldinfo in fi)
{
    Console.WriteLine (fieldinfo.name);
}

Print results:

Figure 1-6 View the public fields in a class
7. Generate objects with reflection, and invoke properties, methods, and fields to manipulate

Reflectionclass rc = new Reflectionclass ();
Type t = RC. GetType ();
Object obj = activator.createinstance (t);
Get ID field
FieldInfo fi = T.getfield ("id");
Assign a value to the ID field
fi. SetValue (obj, 2);
Gets the Name property
PropertyInfo piname = T.getproperty ("Name");
Assign a value to the Name property
piname.setvalue (obj, "Jujianfei", null);
PropertyInfo piage = T.getproperty ("Age");
Piage.setvalue (obj, "n", null);
Get Show method
MethodInfo mi = T.getmethod ("show");
Call Show Method
mi. Invoke (obj, null);
Console.WriteLine ("ID:" + ((reflectionclass) obj). ID);

Print results:

FIG. 1-7 Integrated Application

use of the System.Reflection.Assembly class

The Assembly class can obtain information about an assembly, dynamically load an assembly, find type information in an assembly, and create an instance of that type. Using the Assembly class can reduce the coupling between assemblies, and is beneficial to the rationalization of software structure.
1. Return assembly object by assembly name

Assembly Assembly = Assembly.Load ("ReflectionDemo2");

2. Return assembly object by DLL file name

Assembly Assembly = Assembly.LoadFrom ("ReflectionDemo2.dll");

3, through the Assembly to get the Assembly class

Type t = assembly. GetType ("Reflectiondemo2.reflectionclass"); Parameter must be the full name of the class

4. Get all the classes in the Assembly by Assembly

5, by the name of the assembly reflection

Assembly Assembly = Assembly.Load ("ReflectionDemo2");
Type t = assembly. GetType ("Reflectiondemo2.reflectionclass"); Parameter must be the full name of the class
object o = Activator.CreateInstance (t, "male");
MethodInfo mi = T.getmethod ("show");
Mi. Invoke (O,null);

Print results:

Figure 1-8 Reflection by assembly name
6. Reflect all of the types through the full name of the DLL file

Assembly Assembly = Assembly.LoadFrom ("ReflectionDemo2.dll");
Type[] Tarray = assembly. GetTypes ();
foreach (Type t in Tarray)
{
    if (T.fullname = = "A.B.C")
    {
        object o = activator.createinstance (t);
    }
}
Summary

The example above is the operation of the public-decorated members of the class, which are actually private and protected-decorated members that can also be accessed, for details, see: C # 's play-Reflex, where no more concrete exploration is done.

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.