使用反射,是否可以发现从给定类型派生的所有类型?
据推测,范围仅限于一个组合中。
答案 0 :(得分:36)
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
答案 1 :(得分:28)
var derivedTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
where t.IsSubclassOf(typeof(A))
select t;
答案 2 :(得分:11)
var types = Assembly
.GetExecutingAssembly()
.GetTypes()
.Where(t => typeof(SomeBaseType).IsAssignableFrom(t) &&
t != typeof(SomeBaseType))
.ToArray();
答案 3 :(得分:3)
我重写了@Hath作为扩展方法的优秀答案:
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();