
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
770
|
Chapter 13: Reflection
return (GetSubClasses(asm, baseClassType));
}
public static Type[] GetSubClasses(Assembly asm, Type baseClassType)
{
List<Type> subClasses = new List<Type>( );
foreach(Type type in asm.GetTypes( ))
{
if (type.IsSubclassOf(baseClassType))
{
subClasses.Add(type);
}
}
return (subClasses.ToArray( ));
}
The GetSubClasses method accepts an assembly path string and a second string con-
taining a fully qualified base class name. This method returns a
Type[] of Types repre-
senting the subclasses of the type passed to the
baseClass parameter.
Discussion
The IsSubclassOf method on the Type class allows you to determine whether the cur-
rent type is a subclass of the type passed in to this method.
The following code shows how to use this method:
public static void FindSubClassOfType( )
{
Assembly asm = Assembly.GetExecutingAssembly( );
Type type = Type.GetType("CSharpRecipes.ReflectionUtils+BaseOverrides");
Type[] subClasses = GetSubClasses(asm,type);
// Write out the subclasses for this type.
if(subClasses.Length > 0)
{
Console.WriteLine("{0} is subclassed by:",type.FullName);
foreach(Type t in subClasses)
{
Console.WriteLine("\t{0}",t.FullName);
}
}
}
First you get the assembly path from the current process, and then you set up use of
CSharpRecipes.ReflectionUtils+BaseOverrides ...