如何在 F# 中获取模块的类型 [英] How to get type of the module in F#
问题描述
如何获取模块的System.Type"?
How to get 'System.Type' of the module?
例如模块:
module Foo =
let bar = 1
这不起作用:
printfn "%s" typeof<Foo>.Name
错误是:
The type 'Foo' is not defined
推荐答案
如果有一个 moduleof
操作符肯定会很好...既然没有,那么做你想做的事情的最简单方法可能是使用 F# PowerPack 中的元数据库:
It would certainly be nice to have a moduleof
operator... Since there's not one, the easiest way to do what you want is probably to use the Metadata library in the F# PowerPack:
#r "FSharp.PowerPack.Metadata.dll"
open Microsoft.FSharp.Metadata
// get .NET assembly by filename or other means
let asm = ...
let fasm = FSharpAssembly.FromAssembly asm
let t = fasm.GetEntity("Foo").ReflectionType
不幸的是,这不适用于动态程序集(例如通过 F# Interactive 生成的程序集).您可以使用普通的 System.Reflection
调用来做类似的事情,但这更依赖于对模块采用的编译形式的充分理解.
Unfortunately, this won't work with dynamic assemblies (such as those generated via F# Interactive). You can do something similar using vanilla System.Reflection
calls, but that's more dependent on having a good understanding of the compiled form that your module takes.
这篇关于如何在 F# 中获取模块的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!