
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
766
|
Chapter 13: Reflection
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 ...