Creating an F # Record Through Reflection

How to create a record type in F # using reflection? Thanks

+7
source share
1 answer

You can use FSharpValue.MakeRecord [MSDN] to create an instance of a record, but I don't think in F # to define record types. However, entries are compiled into simple classes, so you can create a class like in C #. TypeBuilder [MSDN] can be a good starting point.

UPDATE

Adding [<CompilationMapping(SourceConstructFlags.RecordType)>] to the type is all that is required to record. Here is an example of how to do this at runtime.

 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 
+15
source

All Articles