How to get type of the module in F#

2019-01-11 22:42发布

How to get 'System.Type' of the module?

For example module:

module Foo =
     let bar = 1

And this does not work:

printfn "%s" typeof<Foo>.Name

Error is:

The type 'Foo' is not defined

标签: reflection f#
4条回答
虎瘦雄心在
2楼-- · 2019-01-11 23:26

You could add a marker type to the module and then discover the module's type from that:

module Foo =  
    type internal Marker = interface end
    let t = typeof<Marker>.DeclaringType
查看更多
成全新的幸福
3楼-- · 2019-01-11 23:30

module name is not a type.

List in List.map and let (a:List<int>) = [1;2;3] are different.

The first List is a module name, the second is a type.

查看更多
男人必须洒脱
4楼-- · 2019-01-11 23:32

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

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.

查看更多
来,给爷笑一个
5楼-- · 2019-01-11 23:43

It can also be done using Quotations. First, define this helper function somewhere:

open Microsoft.FSharp.Quotations.Patterns

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

Then, you can define a module and get its type like this:

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

Hope this helps.

查看更多
登录 后发表回答