Simon Farshid
Simon Farshid

Reputation: 2686

Reflecting over inherited private methods

I wrote this function:

public static MethodInfo[] GetMethods<T>()
{
    return typeof(T).GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
}

It seems to work fine for classes that do not inherit any other type:

class A
{
    private void Foo() { }
}

var methods = GetMethods<A>(); // Contains void Foo()

But when I run the function on a class that inherits another, it fails to get the base class's private methods:

class B : A
{
    private void Bar() { }
}

var methods = GetMethods<B>(); // Contains void Bar(), but not void Foo() :(

I know that I could define void Foo() as protected, but I am dealing with third party code, where I am not able to do so.

So how do I iterate over the private functions of a class and it's parent classes?

Upvotes: 1

Views: 690

Answers (1)

Simon Farshid
Simon Farshid

Reputation: 2686

I have solved this by running GetMethods recursively until I reach the end of the inheritance tree.

public static IEnumerable<MethodInfo> GetMethods(Type type)
{
    IEnumerable<MethodInfo> methods = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

    if (type.BaseType != null)
    {
        methods = methods.Concat(GetMethods(type.BaseType));
    }

    return methods;
}

Upvotes: 3

Related Questions