Warm tip: This article is reproduced from serverfault.com, please click

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

发布于 2020-12-05 01:58:36

Say I am creating an attribute in F# and I apply it to a function as follows:

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

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

How can I retrieve that attribute via reflection?

Ideally I would like to use something along the lines of myFunction.GetType().GetCustomAttributes(true) but that does not work.

Questioner
Dschroer
Viewed
0
Arshia001 2020-12-05 21:35:27

myFunction.GetType() does not work because the F# compiler automatically creates an FSharpFunc<_,_> subclass each time you reference a function. You'd be getting the type of the FSharpFunc, which is not what you need.

To get a function's reflection info, you'd need to find the module in which it lives first. Each module is compiled to a static class, and you can find the function inside that class. So, to get this function:

module MyModule

let myFunc x = x + 1

you'd need to do something like this (I didn't check the code):

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