vendredi 14 juin 2019

Get all derived methods of a method

Given a method in C#, I need to find all methods in subclasses which overrides directly or indirectly that method.

For example, given the following class architecture

abstract class A { public abstract void m(); }
class B : A { public override void m(){}; }
class C : A { public override void m(){}; }
class D : C { public override void m(){}; }
class E : C { public override void m(){}; }
class F : E { public override void m(){}; }
class G : C {  }
class H : G { public override void m(){}; }

Then the derived methods of C.m would be those from the classes D, E, F, H.

I came up with the following solution that seems to work fine but find it somewhat cumbersome. I suspect there is a clever way to do that. Any thought?

    public static IEnumerable<MethodInfo> DerivedMethods(this MethodInfo mi)
    {
        return mi.DeclaringType.Assembly.GetTypes()
            .Where(klass => klass.IsSubclassOf(mi.DeclaringType))
            .Select(subclass => subclass.GetMethods(
                    BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
                .SingleOrDefault(m => m.GetBaseDefinition() == mi.GetBaseDefinition()))
            .Where(x => x != null);
    }






Aucun commentaire:

Enregistrer un commentaire