首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在F#中,如何访问函数的属性?

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

Stack Overflow用户
提问于 2020-12-05 09:58:36
回答 1查看 79关注 0票数 3

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

代码语言:javascript
复制
type MyAttribute(value: int) =
    inherit System.Attribute()
    member this.Value = value

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

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

理想情况下,我希望使用类似于myFunction.GetType().GetCustomAttributes(true)的东西,但这不起作用。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-05 21:35:27

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

要获取函数的反射信息,您需要首先找到它所在的模块。每个模块都被编译成一个静态类,您可以在该类中找到该函数。因此,要获得此函数:

代码语言:javascript
复制
module MyModule

let myFunc x = x + 1

你需要这样做(我没有检查代码):

代码语言:javascript
复制
// 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>()
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65153065

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档