C Sharp

Querying Metadata with Reflection

In tutorial "Introducing Microsoft .NET," I touched on the fact that the compiler generates a Win32-portable executable (PE) comprising mainly MSIL and metadata. One very powerful feature of .NET is that it allows you to write code to access an application's metadata through a process known as reflection. Put simply, reflection is the ability to discover type information at run time.

This tutorial will describe the reflection API and how you can use it to iterate through an assembly's modules and types and to retrieve the different design-time characteristics of a type. You'll also see several advanced usages of reflection, such as dynamically invoking methods and use type information (through late binding) and even creating and executing MSIL code at run time!

The .NET reflection API is actually a lattice of classes-part of which is shown in Figure 16-1-that is defined in the System.Reflection namespace. These classes enable you to logically traverse assembly and type information. You can start at any place in this hierarchy depending on your application's specific design needs.

-

Figure 16-1 Partial .NET System.Reflection class hierarchy.-

Note that these classes encompass a great deal of functionality. Rather than listing every method and field for each class, I will present an overview of the key classes and then show a demo that illustrates the functionality you'd most likely need to incorporate in your applications.

by BrainBellupdated
Advertisement: