简体   繁体   English

如何在F#中将任何记录转换为地图/词典?

[英]How convert any record into a map/dictionary in F#?

I need to serialize arbitrary records into maps/dictionary. 我需要将任意记录序列化为地图/字典。

I imagine my end type look like this: 我想象我的结束类型看起来像这样:

type TabularData= array<Map<string, obj>>

But I have problems in build a generic function that accept any record and turn them into Map. 但是我在构建通用函数时遇到问题,该函数可以接受任何记录并将其转换为Map。

In practice, the best advice is probably to use some existing serialization library like FsPickler . 实际上,最好的建议可能是使用一些现有的序列化库,例如FsPickler However, if you really want to write your own serialization for records, then GetRecordFields (as mentioned in the comments) is the way to go. 但是,如果您真的想为记录编写自己的序列化,则可以使用GetRecordFields (如注释中所述)。

The following takes a record and creates a map from string field names to obj values of the fields. 以下记录并创建从string字段名称到字段的obj值的映射。 Note that it does not handle nested records and it is not particularly fast: 请注意,它不处理嵌套记录,并且它不是特别快:

open Microsoft.FSharp.Reflection

let asMap (recd:'T) = 
  [ for p in FSharpType.GetRecordFields(typeof<'T>) ->
      p.Name, p.GetValue(recd) ]
  |> Map.ofSeq

Here is a little example that calls this with a simple record: 这是一个使用简单记录调用此示例的小示例:

type Person =
  { Name : string 
    Age : int }

asMap { Name = "Tomas"; Age = -1 }

Using the same idea mentioned by Tomas, you can create a IDictionary<K,V> from a record like this: 使用Tomas提到的相同想法,可以从如下记录中创建IDictionary<K,V>

let asDictionary (entity: 'T) =
    seq {
        for prop in FSharpType.GetRecordFields(typeof<'T>) -> 
        prop.Name, prop.GetValue(entity)
    } |> dict

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM