December 2007
Intermediate to advanced
896 pages
19h 57m
English
You have a type and you need to find out whether it is subclassed anywhere in an assembly.
Use the Type.IsSubclassOf method to test all types within a given assembly, which determines whether each type is a subclass of the type specified in the argument to IsSubClassOf:
public static IEnumerable<Type> ListSubClassesForType(this Assembly asm,
Type baseclassType)
{
return from type in asm.GetTypes()
where type.IsSubclassOf(baseclassType)
select type;
}The ListSubClassesForType extension method accepts an assembly path string and a second string containing a fully qualified base class name. This method returns an IEnumerable<Type> representing the subclasses of the type passed to the baseClassparameter.
The IsSubclassOf method on the Type class allows you to determine whether the current 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()
{
Process current = Process.GetCurrentProcess();
// get the path of the current module
string asmPath = current.MainModule.FileName;
Assembly asm = Assembly.LoadFrom(asmPath);
Type type = Type.GetType("CSharpRecipes.Reflection+BaseOverrides"); IEnumerable<Type> subClasses = asm.ListSubClassesForType(type); // write out the subclasses for this type if(subClasses.Count() > 0) { Console.WriteLine("{0} is subclassed by:",type.FullName); foreach(Type t in subClasses) { Console.WriteLine("\t{0}",t.FullName); ...Read now
Unlock full access