[英]How can I declare a function in F# that can be invoked via WebJob's JobHost.CallAsync?
[英]In F#, how can I access attributes on a function?
假設我在 F# 中創建一個屬性,並將其應用於 function,如下所示:
type MyAttribute(value: int) =
inherit System.Attribute()
member this.Value = value
[<My(42)>]
let myFunction() = ()
如何通過反射檢索該屬性?
理想情況下,我想使用類似於myFunction.GetType().GetCustomAttributes(true)
的東西,但這不起作用。
myFunction.GetType()
不起作用,因為 F# 編譯器會在您每次引用 function 時自動創建FSharpFunc<_,_>
子類。 您將獲得FSharpFunc
的類型,這不是您需要的。
要獲取函數的反射信息,您需要首先找到它所在的模塊。 每個模塊編譯成一個static class,在ZA2F2ED4F8DC40C2CBBDZC2A里面可以找到function。 所以,要得到這個 function:
module MyModule
let myFunc x = x + 1
你需要做這樣的事情(我沒有檢查代碼):
// Assuming the code is in the same assembly as the function;
// otherwise, you must find the assembly in which the module lives
let assm = System.Reflection.Assembly.GetExecutingAssembly()
let moduleType = assm.GetType("MyModule")
let func = moduleType.GetMethod("myFunc")
let attrib = func.GetCustomAttribute<MyAttribute>()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.