简体   繁体   English

在 F# 中,如何访问 function 上的属性?

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

Say I am creating an attribute in F# and I apply it to a function as follows:假设我在 F# 中创建一个属性,并将其应用于 function,如下所示:

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.理想情况下,我想使用类似于myFunction.GetType().GetCustomAttributes(true)的东西,但这不起作用。

myFunction.GetType() does not work because the F# compiler automatically creates an FSharpFunc<_,_> subclass each time you reference a function. myFunction.GetType()不起作用,因为 F# 编译器会在您每次引用 function 时自动创建FSharpFunc<_,_>子类。 You'd be getting the type of the FSharpFunc , which is not what you need.您将获得FSharpFunc的类型,这不是您需要的。

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.每个模块编译成一个static class,在ZA2F2ED4F8DC40C2CBBDZC2A里面可以找到function。 So, to get this function:所以,要得到这个 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>()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在F#中声明可以通过WebJob的JobHost.CallAsync调用的函数? - How can I declare a function in F# that can be invoked via WebJob's JobHost.CallAsync? 如何在F#中获取函数参数的名称? - How to get the name of function argument in F#? 我可以抑制F#编译器在IL代码中复制函数吗? - Can I suppress F# compiler making copy of function in IL code? 在F#中,如何判断对象是否为Async &lt;_&gt;,如何将其转换为Async &lt;_&gt;? - In F#, how do I tell if an object is an Async<_>, and how can I cast it to an Async<_>? 如何将System.Reflection.MemberInfo值转换为它表示的F#值? - How can I convert a System.Reflection.MemberInfo value into the F# value it represents? 如何获得两个列表,每个列表都包含 F# 记录的必需属性和可选属性的名称? - How can I get two lists, each containing the names of the required and optional properties of an F# record? F#:区分的联合字段上的属性? - F#: Attributes on discriminated union fields? 检索F#函数的MethodInfo - Retrieve MethodInfo of a F# function 在F#中你如何获得函数的参数? - In F# how do you get the parameters for a function? F# - 如何根据返回类型动态创建异步函数 - F# - How to create an async function dynamically based on return type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM