I have an abstract class:
abstract class AbstractDataExport
{
public string name;
public abstract bool ExportData();
}
I have classes which are derived from 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()
{
...
}
}
Is it possible to do something like this? (Pseudocode:)
foreach (Implementation imp in Reflection.GetInheritedClasses(AbstractDataExport)
{
AbstractDataExport derivedClass = Implementation.CallConstructor();
Console.WriteLine(derivedClass.name)
}
with an output like
CsvExporter
XmlExporter
?
The idea behind this is to just create a new class which is derived from AbstractDataExport so i can iterate through all implementations automatically and add for example the names to a Dropdown-List. I just want to code the derived class without changing anything else in the project, recompile, bingo!
If you have alternative solutions: tell em.
Thanks
This question is related to
c#
reflection
inheritance
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));
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.
It may not be the elegant way but you can iterate all classes in the assembly and invoke Type.IsSubclassOf(AbstractDataExport)
for each one.
Source: Stackoverflow.com