猿问

获取抽象类的所有继承的类

我有一个抽象类:


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中。我只想编写派生类,而不更改项目中的其他任何内容,重新编译,宾果游戏!


如果您有其他解决方案:请告诉em。


谢谢


ABOUTYOU
浏览 957回答 3
3回答

喵喵时光机

这是一个普遍的问题,尤其是在GUI应用程序中,令我惊讶的是,没有BCL类可以直接使用。这是我的方法。public static class ReflectiveEnumerator{&nbsp; &nbsp; static ReflectiveEnumerator() { }&nbsp; &nbsp; public static IEnumerable<T> GetEnumerableOfType<T>(params object[] constructorArgs) where T : class, IComparable<T>&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; List<T> objects = new List<T>();&nbsp; &nbsp; &nbsp; &nbsp; foreach (Type type in&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Assembly.GetAssembly(typeof(T)).GetTypes()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(T))))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; objects.Add((T)Activator.CreateInstance(type, constructorArgs));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; objects.Sort();&nbsp; &nbsp; &nbsp; &nbsp; return objects;&nbsp; &nbsp; }}一些注意事项:不必担心此操作的“成本”-您只需要(希望)执行一次,即使这样它也不会像您想的那样慢。您需要使用,Assembly.GetAssembly(typeof(T))因为您的基类可能在不同的程序集中。您需要使用条件type.IsClass,!type.IsAbstract因为如果您尝试实例化接口或抽象类,它将引发异常。我喜欢强制枚举类实现,IComparable以便可以对它们进行排序。您的子类必须具有相同的构造函数签名,否则它将引发异常。这通常对我来说不是问题

拉风的咖菲猫

假设它们都在同一程序集中定义,则可以执行以下操作:IEnumerable<AbstractDataExport> exporters = typeof(AbstractDataExport)&nbsp; &nbsp; .Assembly.GetTypes()&nbsp; &nbsp; .Where(t => t.IsSubclassOf(typeof(AbstractDataExport)) && !t.IsAbstract)&nbsp; &nbsp; .Select(t => (AbstractDataExport)Activator.CreateInstance(t));

杨魅力

typeof(AbstractDataExport).Assembly 告诉您类型所在的程序集(假设所有程序集都在同一位置)。assembly.GetTypes()为您提供该程序集中的所有类型,或者assembly.GetExportedTypes()为您提供公共类型。遍历类型并使用type.IsAssignableFrom()会告诉您类型是否派生。
随时随地看视频慕课网APP
我要回答