"Turn" to explain reflection in C #

Source: Internet
Author: User

original link point here: A detailed explanation of the reflection in C #Reflection (Reflection) January 02, 2008 Wednesday 11:21

Two real-world examples: 1, B-Ultrasound: Everyone has been 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.
            Note that the common feature of these two examples is that from the outside of an object to understand the structure inside the object, And they all take advantage of the wave's reflection function. 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.            (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 and the classes in modules, 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, custom properties, claim type, and 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.Assemblymain 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 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 pumping An image 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 typemethod of the type class:         GetConstructor (), GetConstructors (): Returns the ConstructorInfo type, Information for obtaining the constructor of the class          GetEvent (), GetEvents (): Returns the EventInfo type, Information for obtaining events of this class          GetField (), GetFields (): Returns the FieldInfo type, Information for obtaining 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 for all members of the class          GetMethod (), GetMethods () : Returns the MethodInfo type, information used to obtain the method of the class          GetProperty (), GetProperties () : Returns the PropertyInfo type, the information used to obtain the properties of the class      can call these members, either by invoking the InvokeMember () method of the type, or by calling MethodInfo, The Invoke () method for PropertyInfo and other classes.                       to view the construction methods in a class:NEWCLASSW NC = new NEWCLASSW ();Type t = NC. GetType (); constructorinfo[] ci = t.getconstructors ();Gets all constructors for the class foreach (ConstructorInfo c in CI)//traversal of each constructor {parameterinfo[] ps = C.getparameters ();Take out all parameters of each constructor, foreach (parameterinfo Pi in PS)//Traverse and print all the 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 typesConstructorInfo ci = t.getconstructor (PT);Constructs an object array as an input parameter to the constructorobject[] obj = new object[2]{"Grayworm", "Hi.baidu.com/grayworm"};Call the constructor to generate the objectobject o = ci.     Invoke (obj); The method that invokes the generated object tests whether the object was generated successfully//((NEWCLASSW) O). Show ();To generate an object with activator: Type t = typeof (NEWCLASSW);                         Constructor parameter object[] obj = new Object[2] {"Grayworm", "Hi.baidu.com/grayworm"}; With Activator's CreateInstance static method, a new object is generated with the objects 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");                      //Assign value          fi to ID field. SetValue (obj, "k001");                      //Get MyName properties          PropertyInfo pi1 = T.getproperty ("MyName");                     //Assign value to MyName property           Pi1. SetValue (obj, "grayworm", null);                       PropertyInfo pi2 = T.getproperty ("MyInfo");                       PI2. SetValue (obj, "hi.baidu.com/grayworm", null);                      //Get Show method          MethodInfo mi = T.getmethod ("show");                      //Call Show Method          mi. Invoke (obj, null); System.Reflection.Assembly classThe 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.returns the Assembly object through the assembly name Assembly-Assembly.Load ("ClassLibrary831");                  Returns the Assembly object through the DLL file name Assembly-Assembly.LoadFrom ("ClassLibrary831.dll"); Get the class in the assembly by assembly type T = the.    GetType ("Classlibrary831.newclass"); The parameter must be the full name of the class through assembly to get all the classes in the 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"); Mi. Invoke (o, null);

   //The full name of the DLL file reflects all of its types     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); }                  }

"Turn" to explain reflection in C #

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.