user2005657
user2005657

Reputation: 627

How to get all methods for class that inherit from a particular type

I have a whole bunch of class that inherit from a base class 'Port'

Does anyone know how to get all the public methods for all classes that inherit from 'Port'

I know I have to call the GetMethods method and you call this off a type.

I figure if I could somehow get a list of all the class inheriting from Port I could go something like:

(All types inheriting from port).SelectMany(x => x.GetMethods());

Can anyone help here?

Upvotes: 2

Views: 476

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503489

Okay, now we know they're in the same assembly, I suspect you want:

var methods = from type in typeof(Port).Assembly.GetTypes()
              where typeof(Port).IsAssignableFrom(type)
              from method in type.GetMethods()
              select method;

aka

var methods = typeof(Port).Assembly.GetTypes()
                          .Where(type => typeof(Port).IsAssignableFrom(type))
                          .SelectMany(type => type.GetMethods());

Note that that will include Port itself in the list of types to fetch.

You might want to use BindingFlags.DeclaredOnly to avoid getting the same methods over and over again - it depends on what you're trying to do with them afterwards.

Upvotes: 2

squillman
squillman

Reputation: 13641

You can use something like this:

Assembly assembly = [get your assembly instance];
Type t = typeof(Port)
var methods = assembly.GetTypes()
                 .Where(p => t.IsAssignableFrom(p))
                 .SelectMany(x => x.GetMethods());

Upvotes: 2

Related Questions