Recipe13.6.Determining and Obtaining Nested Types Within an Assembly


Recipe 13.6. Determining and Obtaining Nested Types Within an Assembly

Problem

You need to determine which types have nested types contained within them in your assembly. Determining the nested types allows you to programmatically examine various aspects of some design patterns. Various design patterns may specify that a type will contain another type; for example, the Decorator and State design patterns make use of object containment.

Solution

Use the DisplayNestedTypes method to iterate through all types in your assembly and list all of their nested types. Its code is:

 public static void DisplayNestedTypes(string asmPath) {     bool output = false;     string line;     Assembly asm = Assembly.LoadFrom(asmPath);     foreach(Type type in asm.GetTypes( ))     {         line = type.FullName + " Contains:\n" ;         output = false;         // Get all nested types.         Type[] nestedTypes = type.GetNestedTypes(                 BindingFlags.Public |                 BindingFlags.NonPublic);         // Roll over the nested types.         foreach (Type t in nestedTypes)         {             line += " " + t.FullName + "\n";             output = true;         }         if (output)             Console.WriteLine(line);     } } 

Discussion

The DisplayNestedTypes method uses an outer foreach loop to iterate over all types in the assembly specified by the asmPath parameter. Within this loop the GetNestedTypes method of the Type class is called to obtain the nested types of the type specified in the type variable.

Usually the dot operator is used to delimit namespaces and types; however, nested types are somewhat special. Nested types are set apart from other types by the + operator in their fully qualified name when dealing with them in the reflection APIs. By passing this fully qualified name in to the static GetType methods, the actual type that it represents can be acquired.

These methods return a Type object that represents the type identified by the typeName parameter.

Calling Type.GetType to retrieve a type defined in a dynamic assembly (one that is created using the types defined in the System.Reflection. Emit namespace) returns a null if that assembly has not already been persisted to disk. Typically you would use the static Assembly.GetType method on the dynamic assembly's Assembly object.


See Also

See Recipe 13.10; see the "Assembly Class" and "BindingFlags Enumeration" topics in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

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