Enumerating Through the Classes in an Assembly


There are a few other tricks you can do once you have a reference to an assembly. Some aren't very practical but they're good to know nonethelessthe one in this section falls under that second category.

It's possible to list all the classes in an assembly. Class information is obtained through a reference to a System.Type object. You learned about System.Type in Chapter 7, "Types." In the following example we obtain an array of System.Type objects for all the classes in the assembly.

To enumerate through all classes in an assembly:

  1. Obtain a reference to an assembly using any of the mechanisms described in "Loading a Program Dynamically," earlier, and store it in a variable, ad for example.

  2. Type foreach (System.Type currtype in ad.GetTypes() ) where currtype is any variable name to store the current System.Type object.

  3. Type an open curly bracket { .

  4. Type Response.Write(currtype.Name + "<br>");

  5. Type a close curly bracket } ( Figure 12.14 ).

    Figure 12.14 GetTypes returns an array of System.Type objects. From there you can navigate through all the items in the array and find information about each type, like its names , its base class's name, etc.
     //using System.Reflection; Assembly ad = Assembly.LoadFrom(@"ordersMemory.DLL"); foreach (System.Type currtype in  ad.GetTypes()  ) {    HttpContext.Current.Response.Write(  currtype.Name  + "<br>"); } 

graphics/tick.gif Tip

  • You can use this technique if you want to generate documentation about an assembly. For example, suppose your boss wants you to write a report of all the classes you have in your DLL. You can write a function where you pass in the name of the assembly, and the function outputs HTML with a list of all the classes in the assembly.




C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

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