dimanche 6 décembre 2020

F# Reflection Expr.NewUnionCase with FSharpType.GetUnionCases and/or Type.MakeGenericType

let recordType = ... // omitted
let resultTypeRaw = typedefof<Result<_,_>>
let resultType = resultTypeRaw.MakeGenericType([|recordType.AsType();typeof<string list>|])
Expr.NewUnionCase(
  (* behavior changes between using resultTypeRaw versus resultType on the next line *)
  FSharpType.GetUnionCases(resultType) |> Array.pick (function | x when x.Name = "Ok" -> Some x | _ -> None),
  [
    Expr.NewRecord(
      recordType,
      [
        Expr.Value(5)
      ]
    )
  ]
)

When I attempt to use resultType with GetUnionCases I get the following exception: Specified method is not supported.. I presume some F# metadata is lost via the call to MakeGenericType.

When I attempt to use resultTypeRaw, GetUnionCases succeeds but the subsequent NewUnionCase fails with the following exception: Type mismatch when building 'sum': incorrect argument type for an F# union. Expected 'T', but received type

How can I construct a union type with dynamic generic arguments or use the result of MakeGenericType with the FSharpType/Expr functions?





Aucun commentaire:

Enregistrer un commentaire