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