简体   繁体   English

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

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

I can create a function to create an option type based on any type:我可以创建一个函数来创建基于任何类型的选项类型:

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

...and I can confirm that the function works: ...我可以确认该功能有效:

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

...and I can create the value "Some 0" by doing this: ...我可以通过这样做来创建值“Some 0”:

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

However, I don't know how to create any other "Some x" value, or how to create "None".但是,我不知道如何创建任何其他“Some x”值,或者如何创建“None”。 (It appears that it creates "Some ", because for strings it's "Some null".) (它似乎创建了“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)

Examples:例子:

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