简体   繁体   中英

Creating record type in F#

I would like to craft a simple record type based on fields provided.

That is :

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

Going directly to type providers looks like heavy gunpower for such a simple task.

Are there any other way ?

update

I found the following question which look very similar Creating F# record through reflection

Putting aside the usefulness of the end result, a snippet below achieves exactly what you asked for in the spirit of 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

A sketch implementation of RecordTypeMaker accepts an arbitrary Record type definition containing type name and array of field names accompanied by field type names . Then behind the curtain it assembles a piece of F# code defining the requested Record type, compiles this code via CodeDom provider , loads container assembly and provides access to this newly created synthetic Record type via Reflection. A test snippet

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

demonstrates for a purely synthetic type myType the proof of concept:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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