反思继承的私有方法

Reflecting over inherited private methods

我写了这个函数:

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

对于不继承任何其他类型的 classes 似乎工作正常:

class A
{
    private void Foo() { }
}

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

但是当我运行继承另一个class上的函数时,它无法获得基础class的私有方法:

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

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

我知道我可以将 void Foo() 定义为 protected,但我正在处理第三方代码,我无法这样做。

那么如何遍历 class 及其父 class 的私有函数?

我已经通过 运行 GetMethods 递归地解决了这个问题,直到我到达继承树的末尾。

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