c# - 反射(reflection)继承的私有(private)方法

标签 c# inheritance reflection

我写了这个函数:

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

它似乎适用于不继承任何其他类型的类:

class A
{
    private void Foo() { }
}

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

但是当我在一个继承另一个类的类上运行该函数时,它无法获取基类的私有(private)方法:

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

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

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

那么如何遍历一个类及其父类的私有(private)函数呢?

最佳答案

我通过递归运行 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;
}

关于c# - 反射(reflection)继承的私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32971571/

相关文章:

C++/多态性/虚函数/为什么我的子类的函数没有被调用?

java - 什么时候使用 super() ?

java - 如何在运行时传递java类作为引用?

c# - sql错误没有返回给调用者

c# - 页面刷新后 ModalPopUpExtender 又出现了?

c# - 如何从派生类中获取属性值?

c# - 使用从通用方法获取的参数调用方法

java - 运行字符串中包含的代码段

c# - 匿名类型的匿名方法未被授权?

c# - 案例陈述的更好替代方案