繁体   English   中英

如何使用 Activator.CreateInstance 创建 F# 选项类型的实例?

[英]How do I create an instance of an F# option type using Activator.CreateInstance?

我可以创建一个函数来创建基于任何类型的选项类型:

let createOptionType typeParam =
    typeof<unit option>.GetGenericTypeDefinition().MakeGenericType([| typeParam |])

...我可以确认该功能有效:

createOptionType (typeof<int>) = (Some 5).GetType() // returns true

...我可以通过这样做来创建值“Some 0”:

System.Activator.CreateInstance(x.GetType(), [| null |]) // returns Some 0

但是,我不知道如何创建任何其他“Some x”值,或者如何创建“None”。 (它似乎创建了“Some”,因为对于字符串,它是“Some null”。)

let makeOptionValue typey v isSome =
    let optionType = createOptionType typey
    let cases = FSharp.Reflection.FSharpType.GetUnionCases(optionType)
    let cases = cases |> Array.partition (fun x -> x.Name = "Some")
    let someCase = fst cases |> Array.exactlyOne
    let noneCase = snd cases |> Array.exactlyOne
    let relevantCase, args =
        match isSome with
        | true -> someCase, [| v |]
        | false -> noneCase, [| |]
    FSharp.Reflection.FSharpValue.MakeUnion(relevantCase, args)

例子:

makeOptionValue typeof<int> 3 true          // returns "Some true"
makeOptionValue typeof<int> null false      // returns "None"

暂无
暂无

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

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