Create Discriminated Union Case from String

前端 未结 3 1063
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 05:32

I\'m trying to create DU cases from strings. The only way I can see doing this is by enumerating over the DU cases via Microsoft.FSharp.Reflection.FSharpType.GetUnionC

3条回答
  •  再見小時候
    2020-12-06 06:26

    As the cases have no value, another option is to use enums:

    type Keyword = 
      | FOO   = 0
      | BAR   = 1
      | BAZ   = 2
      | BLAH  = 3
    
    let strings = ["FOO";"BAR"]
    let keywords = 
      [for s in strings -> s, Keyword.Parse(typeof, s)]
      |> Map.ofList
    

    Then you can simply use Enum.Parse.

提交回复
热议问题