如何获得两个列表,每个列表包含 F# 记录的必需属性和可选属性的名称?
How can I get two lists, each containing the names of the required and optional properties of an F# record?
我有一个 F# 记录类型
type MyType = {
Name : string
Description : string option
}
我想要两个数组,一个包含必需属性的名称,一个包含可选属性。我该怎么做?
open System.Reflection
/// inspired by
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
/// inspired by
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)
这是考虑到@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)
我有一个 F# 记录类型
type MyType = {
Name : string
Description : string option
}
我想要两个数组,一个包含必需属性的名称,一个包含可选属性。我该怎么做?
open System.Reflection
/// inspired by
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
/// inspired by
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)
这是考虑到@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)