在 F# 中,如何访问函数的属性?

In F#, how can I access attributes on a function?

假设我在 F# 中创建一个属性并将其应用于函数,如下所示:

type MyAttribute(value: int) =
    inherit System.Attribute()
    member this.Value = value

[<My(42)>]
let myFunction() = ()

如何通过反射检索该属性?

理想情况下,我想使用类似 myFunction.GetType().GetCustomAttributes(true) 的东西,但这行不通。

myFunction.GetType() 不起作用,因为 F# 编译器会在您每次引用函数时自动创建一个 FSharpFunc<_,_> subclass。您将获得 FSharpFunc 的类型,这不是您所需要的。

要获取函数的反射信息,您首先需要找到它所在的模块。每个模块都被编译成静态的class,你可以在class里面找到函数。所以,要获得这个功能:

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>()