CHAPTER 15 TYPE REFLECTION, LATE BINDING, AND ATTRIBUTE-BASED PROGRAMMING
Table 15-2. Select Members of System.Type
Type
Meaning in Life
IsAbstract
IsArray
IsClass
IsCOMObject
IsEnum
IsGenericTypeDefinition
IsGenericParameter
IsInterface
IsPrimitive
IsNestedPrivate
IsNestedPublic
IsSealed
IsValueType
These properties (among others) allow you to discover a number
of basic traits about the Type you are referring to (e.g., if it is an
abstract entity, an array, a nested class, and so forth).
GetConstructors()
GetEvents()
GetFields()
GetInterfaces()
GetMembers()
GetMethods()
GetNestedTypes()
GetProperties()
These methods (among others) allow you to obtain an array
representing the items (interface, method, property, etc.) you are
interested in. Each method returns a related array (e.g.,
GetFields() returns a FieldInfo array, GetMethods() returns a
MethodInfo array, etc.). Be aware that each of these methods has
a singular form (e.g., GetMethod(), GetProperty(), etc.) that
allows you to retrieve a specific item by name, rather than an
array of all related items.
FindMembers()
This method returns a MemberInfo array based on search criteria.
GetType()
This static method returns a Type instance given a string name.
InvokeMember()
This method allows “late binding” for a given item. You’ll learn
about late binding later in this chapter.
Obtaining a Type Reference Using System.Object.GetType()
You can obtain an instance of the Type class in a variety of ways. However, the one thing you cannot do is
directly create a Type object using the new keyword, as Type is an abstract class. Regarding your first
choice, recall that System.Object defines a method named GetType(), which returns an instance of the
Type class that represents the metadata for the current object.
// Obtain type information using a SportsCar instance.
SportsCar sc = new SportsCar();
Type t = sc.GetType();
Obviously, this approach will only work if you have compile-time knowledge of the type you wish to
reflect over (SportsCar in this case) and currently have an instance of the type in memory. Given this
restriction, it should make sense that tools such as ildasm.exe do not obtain type information by directly
calling System.Object.GetType() for each type, given the ildasm.exe was not compiled against your
custom assemblies.
562