2014-01-12 45 views
0

如何從的一個ProvidedMethod從ProvidedMethod訪問實例

實施也就是說如果foo是提供的類型和刪除類型爲Bar一個叫Execute 方法訪問時(runtime)實例然後給這個代碼

foo.Execute() 

ProvidedMethod等於這個

bar.Execute() //where bar is an object of type Bar 

我有什麼是這個

//p is a MethodInfo that represents Bar.Execute and m is the ProvidedMethod 
objm.InvokeCode <- fun args -> <@@ p.Invoke(--what goes here--,null) @@> 

回答

4

的實例爲args數組中的第一個表達式過去了,所以你可以從那裏訪問它。

此外,您需要構建的InvokeCode不應使用反射捕獲方法信息p並調用Invoke。相反,您需要構建一個F#語句(類似於表達式樹),即表示的調用。

所以,你需要寫是這樣的:我沒有使用<@@ .. @@>這裏,因爲你已經有MethodInfo爲要調用的方法

objm.InvokeCode <- (fun args -> 
    // The 'args' parameter represents expressions that give us access to the 
    // instance on which the method is invoked and other parameters (if there are more) 
    let instance = args.[0] 
    // Now we can return quotation representing a call to MethodInfo 'p' with 'instance' 
    Expr.Call(instance, p)) 

注意。如果您反而想要調用方法ProviderRuntime.DoStuff(instance)那麼您可以使用報價文字:

objm.InvokeCode <- (fun args -> 
    let instance = args.[0] 
    <@@ ProviderRuntime.DoStuff(%%instance) @@>)