What is the Enum.GetName equivalent for F# union member?

后端 未结 3 1105
难免孤独
难免孤独 2020-12-30 00:50

I want to get the equivalent of Enum.GetName for an F# discriminated union member. Calling ToString() gives me TypeName+MemberName, which isn\'t ex

3条回答
  •  生来不讨喜
    2020-12-30 01:38

    @DanielAsher's answer works, but to make it more elegant (and fast? because of the lack of reflection for one of the methods), I would do it this way:

    type Beverage =
        | Coffee
        | Tea
        static member ToStrings() =
            Microsoft.FSharp.Reflection.FSharpType.GetUnionCases(typeof)
                |> Array.map (fun info -> info.Name)
        override self.ToString() =
            sprintf "%A" self
    

    (Inspired by this and this.)

提交回复
热议问题