本文介绍了通过反射创建 F# 记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用反射在 F# 中创建记录类型?谢谢

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

推荐答案

您可以使用 FSharpValue.MakeRecord 来创建记录实例,但我认为 F# 中没有任何用于定义记录类型的东西.但是,记录会编译为简单的类,因此您可以像在 C# 中一样构建一个类.TypeBuilder 可能是一个很好的起点.

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.

[] 添加到类型是使其成为记录所需的全部内容.下面是如何在运行时执行此操作的示例.

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# 记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 00:09