2008-10-18 62 views
2

我想這一點:如何在ThreadContext類中獲取MethodInfo?

Type ThreadContextType = typeof(Application).GetNestedType("ThreadContext", System.Reflection.BindingFlags.NonPublic); 
MethodInfo FDoIdleMi = ThreadContextType.GetMethod("FDoIdle", BindingFlags.NonPublic | 
    BindingFlags.Instance, null, new Type[] { typeof(Int32) }, null); 

ThreadContextType是好,但FDoIdleMi爲空。我知道GetMethod調用有問題,因爲FDoIdle來自UnsafeNativeMethods.IMsoComponent接口。

如何做到這一點?謝謝。

回答

2

你需要完全限定的方法名,因爲他們使用顯式接口實現:

Type type = typeof(Application).GetNestedType("ThreadContext", 
    BindingFlags.NonPublic); 
MethodInfo doIdle = type.GetMethod(
    "System.Windows.Forms.UnsafeNativeMethods.IMsoComponent.FDoIdle", 
    BindingFlags.NonPublic | BindingFlags.Instance); 

根據記錄,反映非公共成員一般是不好的做法,但你可能已經知道那。

編輯在教人以漁的精神,我想通了這一點由類型對象上調用GetMethods(...),並檢查返回數組看到其方法是如何命名。當然,這些名字包括完整的命名空間規範。

+0

我曾嘗試與UnsafeNativeMethods.IMsoComponent.FDoIdle但忘記了System.Windows.Forms前綴。感謝那。 – 2008-10-18 16:37:54

1

這是哈克,但這個工程:

using System; 
using System.Linq; 
using System.Reflection; 
using System.Windows.Forms; 

public class Test 
{ 
    static void Main() 
    { 
     Type clazz = typeof(Application).GetNestedType("ThreadContext", BindingFlags.NonPublic); 
     Type iface = typeof(Form).Assembly.GetType("System.Windows.Forms.UnsafeNativeMethods+IMsoComponent"); 
     InterfaceMapping map = clazz.GetInterfaceMap(iface); 
     MethodInfo method = map.TargetMethods.Where(m => m.Name.EndsWith(".FDoIdle")).Single(); 
     Console.WriteLine(method.Name); 
    } 
} 

有匹配的目標方法的更萬無一失的方法,但這種情況發生的工作這段時間:)

+0

也許不如查理寫的那麼明顯,但非常有趣。 – 2008-10-18 16:46:25

相關問題