问题描述
如何创建F#中的记录类型通过使用反射?谢谢
How can I create a record type in F# by using reflection? Thanks
推荐答案
您可以使用<$c$c>FSharpValue.MakeRecord$c$c>创造纪录的实例,但我不认为有什么烤成F#定义记录的类型的。然而,记录编译成简单的类,这样你就可以建立一个类,你会在C#。 <$c$c>TypeBuilder$c$c>可能是一个很好的起点。
You can use FSharpValue.MakeRecord
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
may be a good starting point.
添加 [&LT; CompilationMapping(SourceConstructFlags.RecordType)GT;]
的类型是所有的需要,使之成为记录。下面是如何在运行时做一个这样的例子。
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
这篇关于通过反射创建F#记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!