Getting all types from an assembly derived from a

2019-04-08 06:24发布

I am trying to examine the contents of an assembly and find all classes in it that are directly or indirectly derived from Windows.Forms.UserControl.

I am doing this:

Assembly dll = Assembly.LoadFrom(filename);
var types = dll.GetTypes().Where(x => x.BaseType == typeof(UserControl));

But it is giving an empty list because none of the classes directly extend UserControl. I don't know enough about reflection to do it quickly, and I'd rather not write a recursive function if I don't have to.

标签: c# reflection
2条回答
兄弟一词,经得起流年.
2楼-- · 2019-04-08 06:45

You should use Type.IsSubclassOf this instead:

var types = dll.GetTypes().Where(x => x.IsSubclassOf(typeof(UserControl)));
查看更多
我命由我不由天
3楼-- · 2019-04-08 06:48

You can use :

    var assembly = Assembly.Load(filename);
    var types = assembly.GetTypes().Where((type) => typeof(UserControl).IsAssignableFrom(type));
查看更多
登录 后发表回答