Created
March 31, 2017 14:44
-
-
Save wolf99/b28286c6887a13993d60c2fcf32012b2 to your computer and use it in GitHub Desktop.
Class that lists all the types derived from a given type. Taken from http://stackoverflow.com/a/6944605/1292918
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Reflection; | |
namespace FooProgram | |
{ | |
public static class DerivedClassEnumerator | |
{ | |
// Class that list all the types derived from a given type | |
// Taken from http://stackoverflow.com/a/6944605/1292918 | |
// - Uses Assembly.GetAssembly(typeof(T)) because the base class might be in a different assembly. | |
// - Use the criteria type.IsClass and !type.IsAbstract because it'll otherwise throw an exception | |
// if it tries to instantiate an interface or abstract class. | |
// - Child classes must have identical constructor signatures, otherwise it'll throw an exception. | |
static DerivedClassEnumerator() { } | |
public static IEnumerable<T> GetObjectsDerivedFromType<T>(params object[] constructorArgs) where T : class//, IComparable<T> | |
{ | |
List<T> objects = new List<T>(); | |
foreach (Type type in Assembly.GetAssembly(typeof(T)).GetTypes() | |
.Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(T)))) | |
{ | |
objects.Add((T)Activator.CreateInstance(type, constructorArgs)); | |
} | |
// If the classes implement IComparable then their objects could be sorted, see Where clause in signature | |
//objects.Sort(); | |
return objects; | |
} | |
public static IEnumerable<string> GetNamesDerivedFromType<T>(params object[] constructorArgs) where T : class | |
{ | |
List<string> names = new List<string>(); | |
foreach (Type type in Assembly.GetAssembly(typeof(T)).GetTypes() | |
.Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(T)))) | |
{ | |
names.Add(((T)Activator.CreateInstance(type, constructorArgs)).ToString()); | |
} | |
names.Sort(); | |
return names; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment