System.Reflection =>查找自定义类

时间:2016-07-30 15:58:56

标签: c#

由于不熟悉System.Reflection,我想知道是否有办法返回从某个自定义类继承的项目中的类。

自定义类 只是一个示例类

public class Parent
{
    public Parent() { }
}

继承的类 再次只是一组示例

public class ParentA : Parent
{
    /*code*/
}

public class Something
{
    /*code*/
}

public class SneakyParent : Parent
{
    /*code*/
}

System.Reflection Code I I Tried 这是当前在控制台应用程序中编写的,但最终将输出到数组或列表

class Program
{
    static void Main(string[] args)
    {
        Assembly assem = typeof(Parent).Assembly;
        foreach (var type in assem.GetTypes())
        {
            Console.WriteLine($"Parent \"{type.Name}\" found!");
        }
        Console.ReadLine();
    }
}

运行代码后,这是我得到的输出:

Parent "Parent" found!
Parent "Program" found!
Parent "ParentA" found!
Parent "Something" found!
Parent "SneakyParent" found!

还有几个“嗯...我想知道”尝试我仍然无法弄清楚如何返回正确的输入,并且无论如何返回类。理想情况下,我希望输出为......

Parent "Parent A" found!
Parent "SneakyParent" found!

...以及将这些类返回到列表或数组中。

1 个答案:

答案 0 :(得分:0)

Assembly assem = typeof(Parent).Assembly;
foreach (var type in assem.GetTypes().Where(x => x.IsSubclassOf(typeof(Parent))))
{
    Console.WriteLine($"Parent \"{type.Name}\" found!");
}
Console.ReadLine();