[英]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
List
和let (a:List<int>) = [1;2;3]
是不同的。
第一個List
是模塊名稱,第二個是類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.