CHAPTER 15 TYPE REFLECTION, LATE BINDING, AND ATTRIBUTE-BASED PROGRAMMING
Source Code The AttributedCarLibrary project is included in the Chapter 15 subdirectory.
Reflecting on Attributes Using Early Binding
Remember that an attribute is quite useless until another piece of software reflects over its values. Once
a given attribute has been discovered, that piece of software can take whatever course of action
necessary. Now, like any application, this “other piece of software” could discover the presence of a
custom attribute using either early binding or late binding. If you wish to make use of early binding,
you’ll require the client application to have a compile-time definition of the attribute in question
(VehicleDescriptionAttribute, in this case). Given that the AttributedCarLibrary assembly has defined
this custom attribute as a public class, early binding is the best option.
To illustrate the process of reflecting on custom attributes, create a new C# Console Application
named VehicleDescriptionAttributeReader. Next, set a reference to the AttributedCarLibrary assembly.
Finally, update your initial *.cs file with the following code:
// Reflecting on attributes using early binding.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AttributedCarLibrary;
namespace VehicleDescriptionAttributeReader
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Value of VehicleDescriptionAttribute *****\n");
ReflectOnAttributesUsingEarlyBinding();
Console.ReadLine();
}
private static void ReflectOnAttributesUsingEarlyBinding()
{
// Get a Type representing the Winnebago.
Type t = typeof(Winnebago);
// Get all attributes on the Winnebago.
object[] customAtts = t.GetCustomAttributes(false);
// Print the description.
foreach (VehicleDescriptionAttribute v in customAtts)
Console.WriteLine("-> {0}\n", v.Description);
}
588
}
}