如何在F#中获取模块的类型 [英] How to get type of the module in F#
本文介绍了如何在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屋!
查看全文