假设我在F#中创建了一个属性,并将其应用于一个函数,如下所示:
type MyAttribute(value: int) =
inherit System.Attribute()
member this.Value = value
[<My(42)>]
let myFunction() = ()如何通过反射检索该属性?
理想情况下,我希望使用类似于myFunction.GetType().GetCustomAttributes(true)的东西,但这不起作用。
发布于 2020-12-05 21:35:27
myFunction.GetType()不起作用,因为F#编译器会在您每次引用函数时自动创建一个FSharpFunc<_,_>子类。您将获得FSharpFunc的类型,而这并不是您所需要的。
要获取函数的反射信息,您需要首先找到它所在的模块。每个模块都被编译成一个静态类,您可以在该类中找到该函数。因此,要获得此函数:
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>()https://stackoverflow.com/questions/65153065
复制相似问题