Recipe 13.6. Determining and Obtaining Nested Types Within an AssemblyProblemYou 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. SolutionUse 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); } } DiscussionThe 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.
See AlsoSee Recipe 13.10; see the "Assembly Class" and "BindingFlags Enumeration" topics in the MSDN documentation. |