CHAPTER 15 TYPE REFLECTION, LATE BINDING, AND ATTRIBUTE-BASED PROGRAMMING
The Type.GetCustomAttributes() method returns an object array that represents all the attributes
applied to the member represented by the Type (the Boolean parameter controls whether the search
should extend up the inheritance chain). Once you have obtained the list of attributes, iterate over each
VehicleDescriptionAttribute class and print out the value obtained by the Description property.
Source Code The VehicleDescriptionAttributeReader project is included under the Chapter 15 subdirectory.
Reflecting on Attributes Using Late Binding
The previous example made use of early binding to print out the vehicle description data for the
Winnebago type. This was possible due to the fact that the VehicleDescriptionAttribute class type was
defined as a public member in the AttributedCarLibrary assembly. It is also possible to make use of
dynamic loading and late binding to reflect over attributes.
Create a new project called VehicleDescriptionAttributeReaderLateBinding and copy
AttributedCarLibrary.dll to the project’s \bin\Debug directory. Now, update your Program class as
follows:
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Text;
using System.Reflection;
namespace VehicleDescriptionAttributeReaderLateBinding
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Value of VehicleDescriptionAttribute *****\n");
ReflectAttributesUsingLateBinding();
Console.ReadLine();
}
private static void ReflectAttributesUsingLateBinding()
{
try
{
// Load the local copy of AttributedCarLibrary.
Assembly asm = Assembly.Load("AttributedCarLibrary");
// Get type info of VehicleDescriptionAttribute.
Type vehicleDesc =
asm.GetType("AttributedCarLibrary.VehicleDescriptionAttribute");
589