c # reflection type and two main classes assembly

1, reflecting what it is?

     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 obtain information about these components in the program run, for example:

 

     Assembly Class Assembly information can be obtained is running, it can also dynamically load assemblies, and to find the type of information in the assembly and creates 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 namespaces and assemblies

   Many people do not know this concept, for a .NET programmer, it is necessary to figure out these concepts.

   Namespace similar to the java package (package), but not exactly the same, because Java packages must be placed in accordance with the table of contents, and .NET is not needed, it only needs to add a reference to the relevant line.

   What accessory is installed? Literally I could not understand what it is in C #, popular talk, before the formation of the final .exe or .dll, and those related things not related (for example, a lot of class) to be packed in bales assembled together, these things are called assembly. Of course, we understand it as a direct exe and dll.

   Relations namespace assembly is not one to one, nor is it included in another, an assembly can have multiple namespaces, a namespace can exist in more than fitting in. Say maybe we do not understand, it would give an example:

 

Copy the code

// assembly A:

namespace N1

{

  public class AC1 {…}

  public class AC2 {…}

}

namespace N2

{

  public class AC3 {…}

  public class AC4{…}

}

// fitting B:

namespace N1

{

  public class BC1 {…}

  public class BC2 {…}

}

namespace N2

{

  public class BC3 {…}

  public class BC4{…}

}

Copy the code

   The two assemblies in both namespace N1, N2, and each declares two classes, this is entirely possible, then we assembly A reference in an application, then we can see in this application N1 is the class AC1, AC2, N2 under class AC3, AC4.

   If we remove the reference to A, then to B references assembly, that in this application, we can only see in the BC3 BC1 at N1, BC2, N2, BC4.

     While references A, B, of course, be able to see all of the above categories.

   Here, we can understand the concept of a namespace which only shows 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.

 

  3, run-time type information to get what is the use

   One 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 the interfaces in their software, 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:

public interface IMediaFormat

{

string Extension {get;}

Decoder GetDecoder();

}

 

  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, the use of some reflections

  The basic concept of reflection is that a few of the above, it reflected what use it?

  (1) acquired by a reflection type

    Acquiring method There are two types: one is to give the object instance

    The times 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 call System.Object GetType method on the statement to obtain an instance of an object type of object, such as in a way, I need to determine whether the parameters passed in to achieve a certain interface, if realized, this interface is a method call:

    …

   public void Process( object processObj )

 

{

Type t = processsObj.GetType();

if( t.GetInterface(“ITest”) !=null )

   …

}

Further a method for acquiring type and Assembly.GetType Type.GetType by methods such as:

      Type t = Type.GetType(“System.String”);

   It should be noted that the foregoing we talked about the relationship between namespaces and assemblies, 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 is declared in mscorlib.dll, above Type t = Type.GetType ( "System.String") is correct

    System.Data.DataTable is declared in System.Data.dll, then:

Type.GetType ( "System.Data.DataTable") can only get a null reference.

    have to:

Type t = Type.GetType("System.Data.DataTable,System.Data,Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");

(2) to traverse the object through the reflection properties

There is a Test entity classes:

Code Sometimes I need to iterate attribute (name and value) or a Test I'm lazy and that entity object classes and attributes particularly large, it can be used in the following ways:

Code is also sometimes can also get information about the browser this way:

Code (3) to dynamically create objects according to the type of

Is the basis of the abstract factory, but also the core technology to achieve the abstract factory through it, you can dynamically create an object that you want. As the following example demonstrates how to dynamically create an instance or EnglishName of ChineseName

 

using System;

using System.Reflection;

namespace TestReflection

{

   class ReflectionExample

    {

        public static void Main()

        {

            IName name=AbstractFactory.GetName();

            name.ShowName();

        }

   }

 

   public class AbstractFactory

   {

       public static IName GetName()

       {

           // value of s after dynamically acquiring from the Web.config

           // assigned to the s: TestReflection.EnglishName, will display the English name

           string s = "TestReflection.ChineseName";

           IName name = (IName)Assembly.Load("TestReflection").CreateInstance(s);

           return name;

       }

   }

 

// declare an interface, it has a "name" function display

public interface IName

{

void ShowName();

}

 

   // implement the interface, display Chinese name

   public class ChineseName : IName

   {

       public void ShowName()

       {

           Console.WriteLine("!");

           Console.ReadLine ( "Chinese name");

       }

   }

 

   // implement the interface, display the name of the United Kingdom

   public class EnglishName:IName

   {

       void IName.ShowName()

       {

           Console.WriteLine("Enslish Name");

           Console.ReadLine();

       }

   }

}

 

Published 224 original articles · won praise 14 · views 40000 +

Guess you like

Origin blog.csdn.net/xulong5000/article/details/105143362