CHAPTER 15 TYPE REFLECTION, LATE BINDING, AND ATTRIBUTE-BASED PROGRAMMING
// Get type info of the Description property.
PropertyInfo propDesc = vehicleDesc.GetProperty("Description");
// Get all types in the assembly.
Type[] types = asm.GetTypes();
// Iterate over each type and obtain any VehicleDescriptionAttributes.
foreach (Type t in types)
{
object[] objs = t.GetCustomAttributes(vehicleDesc, false);
// Iterate over each VehicleDescriptionAttribute and print
// the description using late binding.
foreach (object o in objs)
{
Console.WriteLine("-> {0}: {1}\n",
t.Name, propDesc.GetValue(o, null));
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
If you were able to follow along with the examples in this chapter, this code should be (more or less)
self-explanatory. The only point of interest is the use of the PropertyInfo.GetValue() method, which is
used to trigger the property’s accessor. Here is the output of the current example:
***** Value of VehicleDescriptionAttribute *****
-> Motorcycle: My rocking Harley
-> HorseAndBuggy: The old gray mare, she ain't what she used to be...
-> Winnebago: A very long, slow, but feature-rich auto
Source Code The VehicleDescriptionAttributeReaderLateBinding project is included under the Chapter 15
subdirectory.
590