2015-10-06 64 views
1

我寫了這個功能:反映在繼承私有方法

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,但我正在處理第三方代碼,我無法這樣做。

那麼如何迭代一個類的私有函數,它是父類呢?

+3

見[重複](http://stackoverflow.com/questions/2267277/get-private-properties-method-of-base-class-with-reflection),檢查'Type.BaseType'(而那不是'null'!)。 :) – CodeCaster

+1

私有成員不被繼承,因此派生類型不知道它們(即使通過反射)。 –

+0

投票重新打開,因爲建議的副本只檢查繼承層次深一層,我想發佈我的當前解決方案。 –

回答

3

我已經通過遞歸運行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; 
}