Reflection (C # Programming Guide) reprint

I understand that:

Assembly: Assembly (Assembly)

Late binding: late binding

MSDN: reflection (C # Programming Guide)

----------------- -------- reads as follows

1, what is reflected
2, naming relationship space and fitting
3, run to get the type of information what use
4, how to use reflection to obtain type
5, how to dynamically create objects based on the type
6, how to obtain a method and a dynamic invocation method
7 dynamically create commissioned

1, what is the reflection
        reflection, the Chinese translation for reflection.
        This embodiment is the type of information acquired .Net runtime, .Net applications of several parts: 'Assembly (Assembly)', 'module (Module1)', 'type (class)' composition, and providing a reflection kind of programming, which allows the programmer can get information about these components in the program run, for example:

        assembly information assembly class to get running, you can also dynamically load assemblies, and look in the assembly in type information, and create an instance of that type.
Type class type information object can be obtained, this object contains all the information elements: methods, constructors, properties, etc., these elements can be obtained by the information Type class, and calls it.
The method comprising MethodInfo information can be obtained name of the method, the class parameters, return values, and it can be called.
And so on, as well as FieldInfo, EventInfo and so on, these classes are included in the System.Reflection namespace.

2, the relationship between space and the fitting name of
        a lot of people on this concept may still be quite clear, qualified for .Net programmers, it is necessary to clarify this point.
        Namespace similar to Java package, but not exactly the same, because Java packages must be placed in accordance with the directory structure, the namespace is not required.

        Assembly is the smallest unit of execution of .Net applications, compiled by the .dll, .exe is fitting.

        The relationship between the assembly and namespace is not one to one, nor each other, an assembly which can have multiple namespaces, a namespace can exist in multiple fittings, so he said it might be a little vague, for example :
assembly A:

  1. namespace  N1
  2. {
  3.       public  class  AC1  {…}
  4.       public  class  AC2  {…}
  5. }
  6. namespace  N2
  7. {
  8.       public  class  AC3  {…}
  9.       public  class  AC4{…}
  10. }
Copy the code

Fitting B:

  1. namespace  N1
  2. {
  3.       public  class  BC1  {…}
  4.       public  class  BC2  {…}
  5. }
  6. namespace  N2
  7. {
  8.       public  class  BC3  {…}
  9.       public  class  BC4{…}
  10. }
Copy the code

The two assemblies in both N1 and N2 two namespaces, and each declares two classes, this is entirely possible, then we assembly A reference in an application, then this application, we N1 can see the following classes of AC1 and AC2, N2 following classes of AC3 and AC4.
        Then we remove the reference to A and B together with a reference, then in this application we can see into the following classes N1 BC1 and BC2, N2 below the same.
        If we also references the two assemblies, then N1 below we can see four categories: AC1, AC2, BC1 and BC2.

        Here, we can understand a concept, the namespace is simply stated that a type family, such as some people are Han Chinese, someone is Muslim; and the assembly showed that a type of live, such as someone living in Beijing, was living in Shanghai ; then in Beijing Han people, there are Hui people, Shanghai Han Chinese people, but also the Muslim people, this is not contradictory.

        We said above, the assembly is a type of place of residence, then in a program to be used in a class, you must tell the compiler that this class live child, the compiler can find it, that must reference the assembly.
        So if in the preparation of procedures, perhaps not sure where this class, just know its name, you can not use it? The answer is yes, and this is reflected, to provide the type of address when the program is running, try to find it.
Are interested, then read on.

3, run-time type information obtained by what
        some people might doubt, since in the development will be able to write the code, why do still run into, not only cumbersome, but efficiency is also affected.
This is a matter of debate, just like early binding and late binding, applied to different occasions. Some people oppose late binding, on the grounds that the efficiency loss, but many people enjoy the benefits of a virtual function brings the right time has not yet realized that he had to spend a late binding. This question is open to, not a few words can speak clearly, so we go beyond the.
        My view is, late binding can bring a lot of convenience in design, suitable use can greatly enhance the reusability and flexibility of the program, but everything has two sides, at the right time to use, you need to repeatedly measure.

He went on to say, runtime type information obtained in the end what use is it?
Or give an example to illustrate that many software developers like to leave some of their own software interfaces, others can write some plug-ins to expand the functionality of the software, for example, I have a media player, and I hope we can easily expand recognized format, then I declare an interface:

  1. public  interface  IMediaFormat
  2. {
  3. string  Extension  {get;}
  4. Decoder  GetDecoder();
  5. }
Copy the code

This interface contains a Extension property that returns the extension support, and the other method returns a decoder object (I assume a Decoder class, this class provides the functionality of the file stream decoding, the extension can be derived ), by decoding the object I can explain file stream.
So I require all of decoding plug must derive a decoder, and implement this interface, returns the decoder object GetDecoder method, and the name of its type configuration to my profile inside.
In this case, I do not need at the right time to develop players know the type of format for future expansion, just from the configuration file types now get the names of all decoders, and dynamic object creation media formats, convert it to IMediaFormat interface to use.

This is a reflection of a typical application.


4, how to use reflection to get the type
        first look at how we get the type of information.
        There are two ways to obtain the type of information, one is to get an instance of the object
        at this time go I just get this instance of the object, the object may be a reference to get in the way, perhaps a reference to an interface, but I do not know its exact type, I need to know, then you can obtain an instance of an object by calling the method GetType declared on System.Object type of object, such as in a certain way, I need to determine whether the parameters passed in to achieve a certain interface, if realized , and a method for the interface is invoked:

  1. public  void  Process(  object  processObj  )
  2. {
  3. Type  t  =  processsObj.GetType();
  4. if(  t.GetInterface(“ITest”)  !=null  )
  5.                     …
  6. }
Copy the code

Another type of method of obtaining and Assembly.GetType Type.GetType by methods such as:
              the Type T = Type.GetType ( "System.String The");
        Note that the foregoing we talked about the relationship between the namespace and the fitting, to find a class, you must specify it in the assembly, or by calling GetType instance in the assembly has been obtained above.
        This type of assembly can write only type names, other exception is mscorlib.dll, this type of assembly declared in the name of the assembly can be omitted (.Net assemblies compile time, by default all references mscorlib.dll, unless explicitly specified at compile time does not refer to it), such as:
          System.String statement is in mscorlib.dll, the above Type t = Type.GetType ( "System.String" ) is correct
          System.Data.DataTable in System.Data.dll declared then:
Type.GetType ( "a System.Data.DataTable") can only get a null reference.
          Must:
Type t = Type.GetType ( "a System.Data.DataTable, the System.Data, Version = 1.0.3300.0, Culture = Neutral, PublicKeyToken = b77a5c561934e089");
          so that it can be, we can see below this post:
                ... 2.XML http://expert.csdn.net/Expert/to? the TEMP = .1919977
          qqchen's answer was wonderful


5, how to dynamically create objects based on the type
        System.Activator provides a method to dynamically create objects based on the type , such as creating a DataTable:

  1. Type  t  =  Type.GetType("System.Data.DataTable,System.Data,Version=1.0.3300.0,  Culture=neutral,  PublicKeyToken=b77a5c561934e089");
  2. DataTable  table  =  (DataTable)Activator.CreateInstance(t);
Copy the code

Example Two: creating an object has a configuration parameter

  1. namespace Test Space  
  2. {
  3.   public  class  TestClass
  4.       {
  5.       private  string  _value;
  6.       public  TestClass(string  value)  
  7.     {
  8.       _value=value;
  9.       }
  10.   }
  11. }
  12. Type  t  =  Type.GetType(“TestSpace.TestClass”);
  13. Object [] constructParms = new object [] { "hello"}; // constructor arguments
  14. TestClass  obj  =  (TestClass)Activator.CreateInstance(t,constructParms);
Copy the code

The parameters in order to put an Object array


6, and a method how to obtain the dynamic method invocation

  1. namespace Test Space
  2. {
  3.       public  class  TestClass  {
  4.           private  string  _value;
  5.           public  TestClass()  {
  6.           }
  7.           public  TestClass(string  value)  {
  8.                 _value  =  value;
  9.           }
  10.           public  string  GetValue(  string  prefix  )  {
  11.           if(  _value==null  )
  12.           return  "NULL";
  13.           else
  14.             return  prefix+"  :  "+_value;
  15.             }
  16.             public  string  Value  {
  17. set  {
  18. _value=value;
  19. }
  20. get  {
  21. if(  _value==null  )
  22. return  "NULL";
  23. else
  24. return  _value;
  25. }
  26.             }
  27.       }
  28. }
Copy the code

The above is a simple class that contains a constructor parameter, a GetValue method, a Value property, we can obtain a method by name and call the method, such as:

  1. // get the type information
  2. Type  t  =  Type.GetType("TestSpace.TestClass");
  3. // constructor parameters
  4. object[]  constuctParms  =  new  object[]{"timmy"};
  5. // create an object based on the type
  6. object  dObj  =  Activator.CreateInstance(t,constuctParms);
  7. // method of obtaining information
  8. MethodInfo  method  =  t.GetMethod("GetValue");
  9. // call some method flag, the meaning here is Public and is an instance method, which is the default value
  10. BindingFlags  flag  =  BindingFlags.Public  |  BindingFlags.Instance;
  11. Parameters // GetValue method
  12. object[]  parameters  =  new  object[]{"Hello"};
  13. // call the method, by receiving the return value of an object
  14. object  returnValue  =  method.Invoke(dObj,flag,Type.DefaultBinder,parameters,null);
Copy the code

Calling similar properties and methods, you can refer to the MSDN

7, dynamically created commission
        delegation is foundation in C # realization of events, sometimes inevitable to dynamically create the commission, in fact, also a delegate type: System.Delegate, all the commission is derived from this class
        System.Delegate provides static methods to dynamically create a commission, such as a delegate:

  1. namespace Test Space {
  2.       delegate  string  TestDelegate(string  value);
  3.       public  class  TestClass  {
  4. public  TestClass()  {
  5.                   }
  6.                   public  void  GetValue(string  value)  {
  7.                           return  value;
  8.                   }
  9.         }
  10. }
Copy the code

Example of use:

  1. TestClass  obj  =  new  TestClass();
  2. // get the type, in fact here can be directly used to get the type typeof
  3. Type  t  =  Type.GetType(“TestSpace.TestClass”);
  4. // create a proxy, passing type, create a proxy object and a method name
  5. TestDelegate  method  =  (TestDelegate)Delegate.CreateDelegate(t,obj,”GetValue”);
  6. String  returnValue  =  method(“hello”);
Copy the code

---------------------------------------------------------------------------------

In addition an article on reflection

--------------- ------------------ reads as follows

Reflected Definition: review metadata and gather information about the capabilities of its type. Metadata (the basic data unit after compilation) of the table is a lot, when the compiler or the assembly module, the compiler creates a class definition table, a field definition table, and the like, and a method definition table.
          System.reflection name space contains several classes allow you reflection (parsing) these metadata tables code   

the System.Reflection.Assembly System.Reflection.MemberInfo System.Reflection.EventInfo System.Reflection.FieldInfo System.Reflection.MethodBase the System. Reflection.ConstructorInfo System.Reflection.MethodInfo System.Reflection.PropertyInfo the System.Type following are several classes of the above method: (1) lists the modules, and the program from the list for use in the assembly and loading assembly assembly defined load focus on the type of search and create an instance of that type. (2) Module understanding module assembly comprising a module, and the like, can also get all global methods defined on the module, or other specific non-global method. (3) An understanding of the use ConstructorInfo constructor parameters, access modifiers (e.g. pulic or private) and implementation details (such as the abstract, or virtual) and so on. Use of Type GetConstructors GetConstructor method or to invoke a particular constructor. 









 
 
 
(4) The method of using the name of MethodInfo understanding, return type, parameters, access modifiers (e.g. pulic or private) and implementation details (such as the abstract, or virtual) and so on. Type of GetMethods GetMethod use or method to invoke a particular method. (5) using FiedInfo know the name of the field, the access modifier (e.g., public or private) and implementation details (e.g., static) and the like, and get or set field values. (6) use the name EventInfo on the events, the event handler type data, custom attributes declared type and reflection type, etc., to add or remove an event handler. (7) Use PropertyInfo know the name of the attribute, the data type, the declared type, the reflective type or writable and read-only status, get or set the property value. (8) ParameterInfo know the name of the parameter, the data type, the parameter is an input or output parameter, and the parameter in the method signature location. Reflected the hierarchical model: (Note: many relationship between all levels) 
 
 
 





 

Reflection effect:
1, can create an instance of the type using reflection dynamically bind to an existing object type, or acquired from an existing object type
2, need to focus on the application downloaded from a particular program at runtime into a specific type, so that you can use reflection when implementing a task.
3, the main application and reflection class libraries need to know a type definition, in order to provide more functionality.

Application Notes:
1, real-world applications in very few applications require the use of a reflective type
2, dynamic binding using reflection necessary to compromise
3, some metadata information can not be acquired by reflection
4, some of the reflection type is designed for those developed using the clr compiler development, so you have to realize that not all types of reflection are for everyone.

 

Reflection appDomain assembly:

When you need reflection AppDomain all assemblies included in the following example:
static void the Main
{
       // through all the assemblies GetAssemblies call appDomain
       the foreach (Assembly ASSEM in Appdomain.currentDomain.GetAssemblies ())
      {
       // reflective of the current assembly information
            reflector.ReflectOnAssembly (ASSEM)
      }
}

Description: calling AppDomain object GetAssemblies method returns an array of System.Reflection.Assembly elements.


Reflecting a single assembly:

The above method of talking about all assemblies AppDomain reflection, we can display call an assembly which, system.reflecton.assembly type provides the following three methods:
1, Load method: a method highly recommended, Load method with a flag assembly and load it, load CLR will cause the policy to the assembly, has in the global assembly buffer, the application base directory and private path below to find the assembly, if not find the assembly system exception is thrown
2, LoadFrom method: a transmission path of the assembly file name (including extension), CLR will load you specify the assembly, passed this parameter can not contain any information about the version number, area property, and public key information if the program can not find the specified path set thrown.
3, LoadWithPartialName: Never use this method, because the application can not determine the version and then in the loaded assembly. The only purpose of which is to help customers who use a certain behavior .net framework provided in the test session .Net framework, this method will eventually be abandoned without.

Note: system.AppDomain also provides a Load method, the static Load method he and Assembly is not the same, AppDomain load method is an instance method returns a reference to the assembly, Assembly sent us the static Load packaging assembly according to the value back to the calling AppDomain. avoid using load method AppDomain


Information acquired by the reflection type:

Finished in front of the reflection on the assembly, following the reflection layer model to talk about the third level, the reflection type
a simple example of using reflection to obtain the type of information:

System the using;
the using sytem.reflection;
class REFLECTING {        static void the Main (String [] args)        {              REFLECTING the reflect new new REFLECTING = (); // define a new class itself              // Invoke a assemblies reflecting.exe 




             myAssembly = Assembly.LoadFrom Assembly ( "reflecting.exe")
             reflect.getreflectioninfo (myAssembly); // acquires reflection information
       }

       // definition of a method of acquiring content reflected
       void getreflectioninfo (Assembly MyAssembly)
       {
             type [] = typearr myassemby.Gettypes (); // get the type
             foreach (type type in typearr) // get more information for each type
            {
                   // Get the type of configuration information
                  constructorinfo [] myconstructors = type.GetConstructors;

                 // Get the type of field information
                 fieldinfo [] myfields = type.GetFiedls ()

                 The method of obtaining information //
                 MethodInfo myMethodInfo = type.GetMethods ();

                 // get attribute information
                 propertyInfo [] myproperties = type.GetProperties

                 // Get the event information
                 the EventInfo [] = MyEvents type.GetEvents;
           }
      }
}
Other type object acquired several methods:
. 1, System.Type parameter is a string type, the string must specify the complete name of the type (including the name space)
2, System.Type method provides two examples: GetNestedType, GetNestedTypes
. 3, an example method is provided Syetem.Reflection.Assembly type: GetType, the GetTypes, GetExporedTypes
. 4, provides these examples System.Reflection.Moudle methods: GetType , GetTypes, FindTypes


Members of the reflective type:

members of the reflection type is reflected in the bottom layer hierarchical model data. We can get a member of a type of method by GetMembers type object. If we use the GetMembers with no parameters, it only returns the static variables and instance members of the public definition of this type, we can also return type specified by the parameters set by the member using arguments GetMembers. Detailed description with reference to specific parameters enumerated type system.reflection.bindingflags msdn.

For example:
// Set members need to return a type of content
BindingFlags BF = bingdingFlags.DeclaredOnly | bingdingFlags.Nonpublic | BingdingFlags.Public;
the foreach (int the MemberInfo mi The t.getmembers (BF))
{
       WriteLine (mi.membertype) // output specification the type members
}


Examples of types of reflection created by:

Can be obtained by reflecting the type of assembly, we will be able to create a new instance of the type obtained according to the procedure set type, create objects at run time to achieve late binding function of which is the aforementioned
we can by following a few methods to achieve:
1, System.Activator the CreateInstance method. This method returns a new object. See specific use MSDN
2, the System.Activator on the createInstanceFrom with a similar method, but the need to specify the type and assembly
3, System.Appdomain method: createInstance, CreateInstanceAndUnwrap, CreateInstranceFrom and CreateInstraceFromAndUnwrap
. 4, an example method System.Type the InvokeMember : this method returns a constructor consistent with the parameters passed, and the structure type.
5, System.reflection.constructinfo Invoke instance method of

The reflection type of interface:

If you want to get a set of interfaces for all types of inheritance, you can call Type of FindInterfaces GetInterface or GetInterfaces. All of these methods can only return to the type of the direct successor of the interface, they will not return to inherit from an interface down interface. To return to the interface of the underlying interface must call the above method again.


Reflection of performance:

Clr need to do more work when using reflection to invoke the trigger type or method, or visit a field or attribute: check parameters, check the permissions and so on, so the speed is very slow. So try not to use reflective programming, intends to prepare for a dynamic structure type (late binding) application, may take the place of several ways:
1, through the class hierarchy. Let the compile-time type shows a type derived from the base, generate an instance of the type at runtime, which will be a reference to its base into a variable type, and then call the base type's virtual method.
2, is achieved by the interface. At runtime, an instance of this type of construct, which will be placed in a reference variable which interface type, and then call the virtual methods defined by the interface.
3, achieved through the commission. Let the type implements a method with a name and prototypes are known at compile time delegate match. At runtime configuration example of the first type, and then construct the object and in the name of this method is an example of the commission, and then by calling the method you want to delegate. This working method is relatively made in the previous two methods to be more, with lower efficiency.

 

Individual operation of the program:

Source DLL class:

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Collections;


namespace cn.SwordYang
{

    public class TextClass:System.Web.UI.Page
    {

public static void RunJs(Page _page, string Source)
        {
            _page.ClientScript.RegisterStartupScript(_page.GetType(), "", "<script type=\"text/javascript\">" + Source + ";</script>");

        }

}

}

// calling code

System.Reflection.Assembly ass = Assembly.LoadFrom (Server.MapPath ( " bin / swordyang.dll")); // load the DLL
            the System.Type ass.GetType T = ( "cn.SwordYang.TextClass"); // get types
            object o = System.Activator.CreateInstance (t); // Create instance

            System.Reflection.MethodInfo mi = t.GetMethod ( "RunJs" ); // get method


            mi.Invoke (o, new object [] {this. Page, "alert ( 'test reflection')"}); // call the method

Reflection mode corresponds strategy design pattern.

 

 

Original Address  https://www.cnblogs.com/wangshenhe/p/3256657.html

Guess you like

Origin www.cnblogs.com/871735097-/p/12148399.html