추상 클래스의 모든 상속 된 클래스 가져 오기
이 질문에는 이미 답변이 있습니다.
- 유형 8 답변 의 모든 파생 유형 가져 오기
추상 클래스가 있습니다.
abstract class AbstractDataExport
{
public string name;
public abstract bool ExportData();
}
AbstractDataExport에서 파생 된 클래스가 있습니다.
class XmlExport : AbstractDataExport
{
new public string name = "XmlExporter";
public override bool ExportData()
{
...
}
}
class CsvExport : AbstractDataExport
{
new public string name = "CsvExporter";
public override bool ExportData()
{
...
}
}
이런 식으로 할 수 있습니까? (의사 코드 :)
foreach (Implementation imp in Reflection.GetInheritedClasses(AbstractDataExport)
{
AbstractDataExport derivedClass = Implementation.CallConstructor();
Console.WriteLine(derivedClass.name)
}
다음과 같은 출력으로
CsvExporter
XmlExporter
?
이 아이디어는 AbstractDataExport에서 파생 된 새 클래스를 생성하여 모든 구현을 자동으로 반복하고 예를 들어 Dropdown-List에 이름을 추가 할 수 있도록하는 것입니다. 프로젝트에서 다른 것을 변경하지 않고 파생 클래스를 코딩하고, 다시 컴파일하고, 빙고하고 싶습니다!
대체 솔루션이있는 경우 : 그들에게 말하십시오.
감사
이것은 특히 GUI 응용 프로그램에서 매우 일반적인 문제이므로 기본적으로이 작업을 수행 할 BCL 클래스가 없다는 점에 놀랐습니다. 내가하는 방법은 다음과 같습니다.
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;
}
}
몇 가지 참고 사항 :
- Don't worry about the "cost" of this operation - you're only going to be doing it once (hopefully) and even then it's not as slow as you'd think.
- You need to use
Assembly.GetAssembly(typeof(T))
because your base class might be in a different assembly. - You need to use the criteria
type.IsClass
and!type.IsAbstract
because it'll throw an exception if you try to instantiate an interface or abstract class. - I like forcing the enumerated classes to implement
IComparable
so that they can be sorted. - Your child classes must have identical constructor signatures, otherwise it'll throw an exception. This typically isn't a problem for me.
Assuming they are all defined in the same assembly, you can do:
IEnumerable<AbstractDataExport> exporters = typeof(AbstractDataExport)
.Assembly.GetTypes()
.Where(t => t.IsSubclassOf(typeof(AbstractDataExport)) && !t.IsAbstract)
.Select(t => (AbstractDataExport)Activator.CreateInstance(t));
It may not be the elegant way but you can iterate all classes in the assembly and invoke Type.IsSubclassOf(AbstractDataExport)
for each one.
typeof(AbstractDataExport).Assembly
tells you an assembly your types are located in (assuming all are in the same).
assembly.GetTypes()
gives you all types in that assembly or assembly.GetExportedTypes()
gives you types that are public.
Iterating through the types and using type.IsAssignableFrom()
gives you whether the type is derived.
참고URL : https://stackoverflow.com/questions/5411694/get-all-inherited-classes-of-an-abstract-class
'programing tip' 카테고리의 다른 글
Moq : 재정의 할 수없는 구성원에 대한 잘못된 설정 : x => x.GetByTitle ( "asdf") (0) | 2020.08.08 |
---|---|
Go 빌드 :“패키지를 찾을 수 없음”(GOPATH가 설정되어 있어도) (0) | 2020.08.08 |
psycopg2 커서에서 열 이름 목록을 얻으려면 어떻게해야합니까? (0) | 2020.08.07 |
Axios는 응답 헤더 필드에 액세스합니다 (0) | 2020.08.07 |
jQuery를 사용하여 파일 다운로드 (0) | 2020.08.07 |