簡體   English   中英

在 F# 中,如何訪問 function 上的屬性?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM