在F#中创建记录类型

时间:2012-04-14 07:34:35

标签: f# type-providers

我想根据提供的字段制作一个简单的记录类型。

那是:

let rectype = MakeRecordType(['fieldname1'; 'fieldname2'])

直接进入类型提供者看起来像是一个如此简单的任务的重枪手。

还有其他方法吗?

更新

我发现以下问题看起来非常相似 Creating F# record through reflection

1 个答案:

答案 0 :(得分:5)

不考虑最终结果的有用性,下面的代码段完全按照my other related answer的精神实现了您的要求:

#if INTERACTIVE
#r @"C:\Program Files (x86)\Microsoft F#\v4.0\FSharp.Compiler.dll"
#r @"C:\Program Files (x86)\FSharpPowerPack-1.9.9.9\bin\FSharp.Compiler.CodeDom.dll"
#endif

open System 
open System.CodeDom.Compiler 
open Microsoft.FSharp.Compiler.CodeDom
open Microsoft.FSharp.Reflection

type RecordTypeMaker (typeName: string, records: (string*string) []) = 
    let _typeDllName = "Synth"+typeName+".dll"
    let _code = 
        let fsCode = new System.Text.StringBuilder()
        fsCode.Append("module ").Append(typeName).Append(".Code\ntype ").Append(typeName).Append(" = {") |> ignore
        for rec' in records do fsCode.Append("  ").Append(fst rec').Append(" : ").Append(snd rec').Append(";\n") |> ignore
        fsCode.Append("}").ToString()
    let _compiled =
        use provider = new FSharpCodeProvider() 
        let options = CompilerParameters([||], _typeDllName) 
        let result = provider.CompileAssemblyFromSource( options, [|_code|] ) 
        result.Errors.Count = 0
    let mutable _type: Type = null

    member __.RecordType
        with get() = if _compiled && _type = null then
                         _type <- Reflection.Assembly.LoadFrom(_typeDllName).GetType(typeName+".Code+"+typeName)
                     _type

RecordTypeMaker的草图实现接受包含Record typetype name数组并伴随field names的任意field type names定义。然后在幕后它组装了一段定义所请求记录类型的F#代码,通过CodeDom provider编译此代码,加载容器程序集并通过Reflection提供对这个新创建的合成Record类型的访问。测试片段

let myType = RecordTypeMaker("Test", [|("Field1", "string"); ("Field2", "int")|]).RecordType
printfn "IsRecordType=%b" (FSharpType.IsRecord(myType))
printfn "Record fields: %A" (FSharpType.GetRecordFields(myType))

演示了纯合成类型myType的概念证明:

IsRecordType=true
Record fields: [|System.String Field1; Int32 Field2|]