[英]Creating F# record through reflection
How can I create a record type in F# by using reflection? 如何使用反射在F#中创建记录类型? 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 . 您可以使用
FSharpValue.MakeRecord
[MSDN]来创建记录实例,但我认为F#中没有任何内容可用于定义记录类型 。 However, records compile to simple classes, so you could build a class as you would in C#. 但是,记录编译为简单类,因此您可以像在C#中一样构建类。
TypeBuilder
[MSDN] may be a good starting point. TypeBuilder
[MSDN]可能是一个很好的起点。
Adding [<CompilationMapping(SourceConstructFlags.RecordType)>]
to the type is all that's required to make it a record. 将
[<CompilationMapping(SourceConstructFlags.RecordType)>]
到该类型是使其成为记录所需的全部内容。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.