Chapter 12: Reflection


Overview

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

This list represents a great deal of functionality and encompasses some of the most powerful and complex capabilities provided by the .NET Framework class library. Unfortunately, this chapter does not have the space to cover all the capabilities of reflection, so it focuses on those elements you are likely to use frequently.

The discussion begins with custom attributes, a mechanism that allows you to associate custom metadata with program elements. This metadata is created at compile time and embedded in an assembly. You can then inspect the metadata at runtime using some of the capabilities of reflection.

After looking at custom attributes, the chapter also looks at some of the fundamental classes that enable reflection, including the System.Type and System.Reflection.Assembly classes, which provide the access points for much of what you can do with reflection.

To demonstrate custom attributes and reflection, you will develop an example based on a company that regularly ships upgrades to its software, and wants to have details of these upgrades documented automatically. In the example, you define custom attributes that indicate the date when program elements were last modified, and what changes were made. You then use reflection to develop an application that looks for these attributes in an assembly, and can automatically display all the details about what upgrades have been made to the software since a given date.

Another example in this chapter considers an application that reads from or writes to a database and uses custom attributes as a way of marking which classes and properties correspond to which database tables and columns. By reading these attributes from the assembly at runtime, the program is able to automatically retrieve or write data to the appropriate location in the database, without requiring specific logic for each table or column.




Professional C# 2005 with .NET 3.0
Professional C# 2005 with .NET 3.0
ISBN: 470124725
EAN: N/A
Year: 2007
Pages: 427

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net