Create Discriminated Union Case from String

前端 未结 3 1065
佛祖请我去吃肉
佛祖请我去吃肉 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:03

    I found this handy code snippet...

    open Microsoft.FSharp.Reflection
    
    let toString (x:'a) = 
        let (case, _ ) = FSharpValue.GetUnionFields(x, typeof<'a>)
        case.Name
    
    let fromString<'a> (s:string) =
        match FSharpType.GetUnionCases typeof<'a> |> Array.filter (fun case -> case.Name = s) with
        |[|case|] -> Some(FSharpValue.MakeUnion(case,[||]) :?> 'a)
        |_ -> None
    

    ... which makes it easy to tack on two lines of code to any DU...

    type A = X|Y|Z with
        override this.ToString() = FSharpUtils.toString this
        static member fromString s = FSharpUtils.fromString s
    

提交回复
热议问题