我写了这个函数:
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/