使用reflection发现派生types
使用reflection,是否有可能发现从给定types派生的所有types?
据推测,范围将被限制在一个单一的大会。
几乎和达林一样,但是在这里你走了
public static List<Type> FindAllDerivedTypes<T>() { return FindAllDerivedTypes<T>(Assembly.GetAssembly(typeof(T))); } public static List<Type> FindAllDerivedTypes<T>(Assembly assembly) { var derivedType = typeof(T); return assembly .GetTypes() .Where(t => t != derivedType && derivedType.IsAssignableFrom(t) ).ToList(); }
用于:
var output = FindAllDerivedTypes<System.IO.Stream>(); foreach (var type in output) { Console.WriteLine(type.Name); }
输出:
NullStream SyncStream __ConsoleStream BufferedStream FileStream MemoryStream UnmanagedMemoryStream PinnedBufferMemoryStream UnmanagedMemoryStreamWrapper IsolatedStorageFileStream CryptoStream TailStream
var derivedTypes = from t in Assembly.GetExecutingAssembly().GetTypes() where t.IsSubclassOf(typeof(A)) select t;
var types = Assembly .GetExecutingAssembly() .GetTypes() .Where(t => typeof(SomeBaseType).IsAssignableFrom(t) && t != typeof(SomeBaseType)) .ToArray();
我重写了@哈斯作为扩展方法的出色答案:
public static class TypeExtensions { public static List<Type> GetAllDerivedTypes(this Type type) { return Assembly.GetAssembly(type).GetAllDerivedTypes(type); } public static List<Type> GetAllDerivedTypes(this Assembly assembly, Type type) { return assembly .GetTypes() .Where(t => t != type && type.IsAssignableFrom(t)) .ToList(); } }
用法:
var listOfDerived = typeof(MyClass).GetAllDerivedTypes();