简体   繁体   中英

Creating F# record through reflection

How can I create a record type in F# by using reflection? Thanks

You can use FSharpValue.MakeRecord [MSDN] to create a record instance, but I don't think there's anything baked into F# for defining record types . However, records compile to simple classes, so you could build a class as you would in C#. TypeBuilder [MSDN] may be a good starting point.

UPDATE

Adding [<CompilationMapping(SourceConstructFlags.RecordType)>] to the type is all that's required to make it a record. Here's an example of how to do this at run-time.

let asmName = AssemblyName("Foo")
let asm = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndCollect)
let moduleBldr = asm.DefineDynamicModule("Test")
let typeBldr = moduleBldr.DefineType("MyRecord", TypeAttributes.Public)
let attrBldr = CustomAttributeBuilder(
                typeof<CompilationMappingAttribute>.GetConstructor([|typeof<SourceConstructFlags>|]), 
                [|box SourceConstructFlags.RecordType|])
typeBldr.SetCustomAttribute(attrBldr)
let typ = typeBldr.CreateType()
printfn "%b" <| FSharpType.IsRecord(typ) //true

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