反射

 

Reflection is a generic term that describes the ability to inspect and manipulate program elements at runtime. For example, reflection allows you to:

  • Enumerate the members of a type

  • Instantiate a new object

  • Execute the members of an object

  • Find out information about a type

  • Find out information about an assembly

  • Inspect the custom attributes applied to a type

  • Create and compile a new assembly

Although previously referred to as a class, Type is an abstract base class. Whenever you instantiate a Type object, you are actually instantiating a class derived from Type. Type has one derived class corresponding to each actual data type, though in general the derived classes simply provide different overloads of the various Type methods and properties that return the correct data for the corresponding data type. They do not generally add new methods or properties. In general, three common ways exist of obtaining a Type reference that refers to any given type:

  • You can use the C# typeof operator as Type t = typeof(double). This operator takes the name of the type (not in quote marks, however) as a parameter.

  • You can use the GetType() method, which all classes inherit from System.Object:

    double d = 10;
    Type t = d.GetType();

    GetType()is called against a variable, rather than taking the name of a type. Note, however, that the Type object returned is still associated with only that data type. It does not contain any information that relates to that instance of the type. The GetType() method can be useful if you have a reference to an object, but are not sure what class that object is actually an instance of.

  • You can call the static method of the Type class, GetType():

    Type t = Type.GetType("System.Double");    

Type is really the gateway to much of the reflection functionality. It implements a huge number of methods and properties — far too many to provide a comprehensive list here. However, the following subsections should give you some idea of the kinds of things you can do with the Type class. Note that the available properties are all read-only; you use Type to find out about the data type — you can't use it to make any modifications to the type!

posted @ 2009-03-06 20:37  Revive and Strive  阅读(323)  评论(1编辑  收藏  举报