通过反射创建F#记录

编程入门 行业动态 更新时间:2024-10-08 19:41:47
本文介绍了通过反射创建F#记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

推荐答案

您可以使用FSharpValue.MakeRecord[MSDN]创造纪录的实例,但我不认为有什么烤成F#定义记录的类型的。然而,记录编译成简单的类,这样你就可以建立一个类,你会在C#。 TypeBuilder[MSDN]可能是一个很好的起点。

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.

添加 [< 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#记录

本文发布于:2023-10-19 01:56:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1506046.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:反射

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!