CHAPTER 15 TYPE REFLECTION, LATE BINDING, AND ATTRIBUTE-BASED PROGRAMMING
function named DisplayCompanyData() before exiting the foreach scope. Notice this method takes a
single System.Type parameter.
private bool LoadExternalModule(string path)
{
...
foreach (Type t in theClassTypes)
{
...
// Show company info.
DisplayCompanyData(t);
}
return foundSnapIn;
}
Using the incoming type, simply reflect over the [CompanyInfo] attribute, like so:
private void DisplayCompanyData(Type t)
{
// Get [CompanyInfo] data.
var compInfo = from ci in t.GetCustomAttributes(false) where
(ci.GetType() == typeof(CompanyInfoAttribute))
select ci;
// Show data.
foreach (CompanyInfoAttribute c in compInfo)
{
MessageBox.Show(c.CompanyUrl,
string.Format("More info about {0} can be found at", c.CompanyName));
}
}
Figure 15-9 shows one possible run.
Figure 15-9. Snapping in external assemblies
Excellent! That wraps up the example application. I hope you can see that the topics presented in
this chapter can be quite helpful in the real world and are not limited to the tool builders of the world.
597