.NET:获取从特定类派生的所有类

Sha*_*air 4 .net oop reflection inheritance attributes

我有一个自定义控件和从它派生的一些控件.我需要获取当前程序集中派生自主类的所有类并检查它们的属性.怎么做到这一点?

Ben*_*n M 12

var type = typeof(MainClass);

var listOfDerivedClasses = Assembly.GetExecutingAssembly()
    .GetTypes()
    .Where(x => x.IsSubclassOf(type))
    .ToList();

foreach (var derived in listOfDerivedClasses)
{
   var attributes = derived.GetCustomAttributes(typeof(TheAttribute), true);

   // etc.
}
Run Code Online (Sandbox Code Playgroud)