var listOfBs = (
from domainAssembly in AppDomain.CurrentDomain.GetAssemblies()
// alternative: from domainAssembly in domainAssembly.GetExportedTypes()
from type in domainAssembly.GetTypes()
where typeof(B).IsAssignableFrom(type)
// alternative: && type != typeof(B)
// alternative: && ! type.IsAbstract
// alternative: where type.IsSubclassOf(typeof(B))
select type).ToArray();
다른 버전
var listOfBs = AppDomain.CurrentDomain.GetAssemblies()
// alternative: .GetExportedTypes()
.SelectMany(domainAssembly => domainAssembly.GetTypes())
.Where(type => typeof(B).IsAssignableFrom(type)
// alternative: => type.IsSubclassOf(typeof(B))
// alternative: && type != typeof(B)
// alternative: && ! type.IsAbstract
).ToArray();
다른 버전
var result = System.Reflection.Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t => t.BaseType != null && t.BaseType.IsGenericType &&
t.BaseType.GetGenericTypeDefinition() == typeof(GenericClass<>));
인스턴스를 생성하는 버전
IEnumerable<AbstractDataExport> exporters = typeof(AbstractDataExport)
.Assembly.GetTypes()
.Where(t => t.IsSubclassOf(typeof(AbstractDataExport)) && !t.IsAbstract)
.Select(t => (AbstractDataExport)Activator.CreateInstance(t));
리스트를 활용한 버전
public static class ReflectiveEnumerator
{
static ReflectiveEnumerator() { }
public static IEnumerable<T> GetEnumerableOfType<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));
}
objects.Sort();
return objects;
}
}
c# - Get all derived types of a type - Stack Overflow
c# - Get all inherited classes of an abstract class - Stack Overflow
c# - Find all derived types of generic class - Stack Overflow
'프로그래밍 언어 > C#' 카테고리의 다른 글
[C#] 4.0 필수 매개변수 및 선택적 매개변수 (0) | 2023.09.22 |
---|---|
[C#] 생성자와 상속 (0) | 2023.09.22 |
[C#] event (이벤트) 개념 (0) | 2023.09.18 |
[C#] default와 new() 제약조건 사용하기 (0) | 2023.08.23 |
[C#] 제네릭 메서드(Generic Method) 널(Null) 반환 방법 (0) | 2023.08.23 |