简体   繁体   中英

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:

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". (It appears that it creates "Some ", because for strings it's "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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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