开发者

.NET: Get all classes derived from specific class

I have a custom control and a number of c开发者_如何学Pythonontrols derived from it. I need to get all classes in the current assembly that are derived from the main class and check their attributes. How to accomplish this?


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.
}


You can use reflection:

Type baseType = ...
var descendantTypes =
    from type in baseType.Assembly.GetTypes()
    where !type.IsAbstract
       && type.IsSubclassOf(baseType)
       && type.IsDefined(typeof(TheCustomAttributeYouRequire), true)
    select type;

You can go from there.


To find derivatives of a class, which were all defined in another Assembly (GetExecutingAssembly didn't work), I used:

var asm = Assembly.GetAssembly(typeof(MyClass));
var listOfClasses = asm.GetTypes().Where(x => x.IsSubclassOf(typeof(MyClass)));

(split over 2 lines to save scrolling)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜