简体   繁体   English

如何获得两个列表,每个列表都包含 F# 记录的必需属性和可选属性的名称?

[英]How can I get two lists, each containing the names of the required and optional properties of an F# record?

I have an F# Record type我有一个 F# 记录类型

type MyType = {
  Name : string
  Description : string option
}

I'd like to get two arrays, one containing the names of the required properties and one containing the optional properties.我想要两个 arrays,一个包含必需属性的名称,一个包含可选属性。 How can I do this?我怎样才能做到这一点?

open System.Reflection

/// inspired by https://stackoverflow.com/questions/20696262/reflection-to-find-out-if-property-is-of-option-type
let isOption (p : PropertyInfo) =
    p.PropertyType.IsGenericType &&
    p.PropertyType.GetGenericTypeDefinition() = typedefof<Option<_>>

/// required and optional property names of a type 'T - in that order
/// inspired by https://stackoverflow.com/questions/14221233/in-f-how-to-pass-a-type-name-as-a-function-parameter
/// inspired by https://stackoverflow.com/questions/59421595/is-there-a-way-to-get-record-fields-by-string-in-f
let requiredAndOptionalPropertiesOf<'T> =
    let optionals, requireds = typeof<'T>.GetProperties() |> Array.partition isOption
    let getNames (properties : PropertyInfo[]) = properties |> Array.map (fun f -> f.Name)
    (getNames requireds, getNames optionals)

Here is an alternative answer that takes into account the comment by @Asti:这是考虑到@Asti评论的替代答案:

open System.Reflection

let isOption (p : PropertyInfo) =
    p.PropertyType.IsGenericType &&
    p.PropertyType.GetGenericTypeDefinition() = typedefof<Option<_>>

let requiredAndOptionalPropertiesOf<'T> =
    let optionals, requireds = FSharp.Reflection.FSharpType.GetRecordFields typeof<'T> |> Array.partition isOption
    let getNames (properties : PropertyInfo[]) = properties |> Array.map (fun f -> f.Name)
    (getNames requireds, getNames optionals)

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

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