繁体   English   中英

如何在F#中获取模块的类型

[英]How to get type of the module in F#

如何获得模块的'System.Type'?

例如模块:

module Foo =
     let bar = 1

这不起作用:

printfn "%s" typeof<Foo>.Name

错误是:

The type 'Foo' is not defined

您可以向模块添加标记类型,然后从中发现模块的类型:

module Foo =  
    type internal Marker = interface end
    let t = typeof<Marker>.DeclaringType

这肯定是有一个好的moduleof操作......因为有没有一个,做你想做的可能是使用元数据库在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生成的程序集)。 您可以使用vanilla System.Reflection调用执行类似的操作,但这更依赖于对模块所采用的编译表单的充分理解。

它也可以使用报价来完成。 首先,在某处定义这个辅助函数:

open Microsoft.FSharp.Quotations.Patterns

let getModuleType = function
| PropertyGet (_, propertyInfo, _) -> propertyInfo.DeclaringType
| _ -> failwith "Expression is no property."

然后,您可以定义一个模块并获取其类型:

module SomeName =
    let rec private moduleType = getModuleType <@ moduleType @>

希望这可以帮助。

模块名称不是类型。

List.map Listlet (a:List<int>) = [1;2;3]是不同的。

第一个List是模块名称,第二个是类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM