获取 StringEnum 的名称

Fetching names of StringEnum

有没有办法获取寓言中 StringEnum 的所有案例?

如果我使用的是 dotnet,我可能会这样做:

 FSharpType.GetUnionCases(t, true)
      |> Array.map(fun i ->
        i.GetCustomAttributes ()
        |> Array.tryPick (function
        | :? CompiledNameAttribute as att -> Some att.CompiledName
        | _ -> None)
        |> Option.defaultWith (fun () -> i.Name)
        |> fun name ->
          let ctor = FSharpValue.PreComputeUnionConstructor i
          let inst = ctor [||]
          (name, inst))

但是,我不能在寓言中使用该方法。 (我不能打字测试。)我有什么选择?

Fable 支持 .NET 反射的有限子集API。

也许这适用于您的用例?

open System
open System.Reflection
open FSharp.Reflection

type Fruit =
| Apple
| Banana
| Cherry

let unionCases (t : Type) =
  [
    for uci in FSharpType.GetUnionCases(t, true) do
      let name = uci.Name
      let value = FSharpValue.MakeUnion(uci, [||])

      name, value
  ]

for name, value in unionCases typeof<Fruit> do
    printfn "\"%s\" -> %A" name value

输出

"Apple" -> Apple 
"Banana" -> Banana 
"Cherry" -> Cherry