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

时间:2018-08-22 22:52:31

标签: .net reflection f#

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

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”。)

1 个答案:

答案 0 :(得分:1)

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"