【问题标题】:Reflecting over inherited private methods反映继承的私有方法
【发布时间】:2015-10-06 22:02:00
【问题描述】:

我写了这个函数:

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()

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

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

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

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

那么我如何迭代一个类的私有函数和它的父类呢?

【问题讨论】:

  • 查看duplicate,查看Type.BaseType(虽然那不是null!)。 :)
  • 私有成员不被继承,因此派生类型不知道它们(即使通过反射)。
  • 投票重新打开,因为建议的副本只检查了一层深的继承层次结构,我想发布我当前的解决方案。

标签: c# inheritance reflection


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 2010-12-07
    • 1970-01-01
    相关资源
    最近更新 更多