Raheel Khan
Raheel Khan

Reputation: 14777

Determining derived classes through reflection

I want to process the Methods of classes derived from class A. Class A and the derived classes reside in different assemblies. I use reflection to get all System.Type's from the derived assembly and iterate through their methods.

Assembly A: class Template {...}
Assembly B: class X: A.Template {...}
Assembly B: class Y: A.Template {...}
Assembly B: class Z: A.Template {...}

When I try to iterate the methods of class X in assembly B, it includes all methods of class A. What I want to achieve is to iterate through only those methods that exist in derived classes.

I don't think that being in different assemblies matters at all but even when I try to filter the method's declaring type based on the assembly, it does not work.

I have tried using various properties of the MethodInfo object but have not been able to filter this out. I am sure I'm missing some silly check but have been struggling with this for long enough.

Any advice would be appreciated.

Upvotes: 2

Views: 1714

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 148980

You can use this to get all derived types in an assembly:

Assembly b = Assembly.LoadFrom(@"c:\B.dll");
var derivedTypes = b.GetTypes().Where(t => typeof(Template).IsAssignableFrom(t));

And this to find any methods defined on that type:

Type derived = ...
var methods = derived.GetMethods(BindingFlags.Instance | 
                                 BindingFlags.Public | 
                                 BindingFlags.DeclaredOnly);

Or this:

var methods = derived.GetMethods().Where(m => m.DeclaringType == derived);

However, if you want to find methods defined on any subclass of Template (e.g. a subclass of X), use this:

Type templateType = typeof(Template);
Type derived = ...
var methods = derived.GetMethods()
                     .Where(m => templateType.IsAssignableFrom(m.DeclaringType) &&
                                 templateType != m.DeclaringType);

Upvotes: 4

Related Questions