Pages

Thursday, February 12, 2009

REFLECTION AND ATTRIBUTES (Part Three) - The System.Reflection Namespace

You can see that the Type.Getxxx methods return arrays of objects created from classes defined in the reflection namespace. For example, GetFields() returns a FieldInfo array representing a type’s fields, and GetMethods() returns a MethodInfo array. All of the reflection classes that identify and provide information about type members are derived from the System.Reflection.MemberInfo class. Figure 19-1 shows the class hierarchy.

System.Reflection.MemberInfo class.

 

Figure 19-1 - Inheritance hierarchy of MemberInfo classes

System.Reflection.MemberInfo
|-----System.Type
|-----System.Reflection.EventInfo
|-----System.Reflection.FieldInfo
|-----System.Reflection.PropertyInfo
|-----System.Reflection.MethodBase
       |-----System.Reflection.ConstructorInfo
       |-----System.Reflection.MethodInfo

It may seem a bit odd that System.Type derives from MemberInfo; after all, a type contains members. However, recall that a Form inherits from a Control although a Form contains controls. In both cases the hierarchy is one of inheritance, not containment. 

The two base classes in Figure 19-1, MemberInfo and MethodBase, define members that play a crucial role in reflection for all their derived types. Here are some of the members you will find most useful:

MemberInfo
• Name—Returns the name of the member.
• Module—Returns the module in which the member is declared.
• GetCustomAttributes—Method that returns the attributes
attached to a member.


MethodBase
• IsAbstract, IsGenericMethod, IsStatic, IsVirtual—Properties
that describe the method.
• GetGenericArguments—Returns the type arguments of a generic method.
• GetParameters—Returns the parameters of the method or constructor.
• Invoke—Invokes a method or constructor. (See “Reflection and Late Binding” on the succeeding posts)

Related topic:

REFLECTION AND ATTRIBUTES (Part One)
REFLECTION AND ATTRIBUTES (Part Two) - The System.Type Members