什么是F#union成员的Enum.GetName等价物?

Dmi*_*ruk 20 f# discriminated-union

我希望得到Enum.GetName一个F#区别联盟成员的等价物.调用ToString()给了我TypeName + MemberName,这不是我想要的.当然,我可以将它归入其中,但是它安全吗?或许还有更好的方法?

Dan*_*her 30

您需要使用Microsoft.FSharp.Reflection命名空间中的类,以便:

open Microsoft.FSharp.Reflection

///Returns the case name of the object with union type 'ty.
let GetUnionCaseName (x:'a) = 
    match FSharpValue.GetUnionFields(x, typeof<'a>) with
    | case, _ -> case.Name  

///Returns the case names of union type 'ty.
let GetUnionCaseNames <'ty> () = 
    FSharpType.GetUnionCases(typeof<'ty>) |> Array.map (fun info -> info.Name)

// Example
type Beverage =
    | Coffee
    | Tea

let t = Tea
> val t : Beverage = Tea

GetUnionCaseName(t)
> val it : string = "Tea"

GetUnionCaseNames<Beverage>()
> val it : string array = [|"Coffee"; "Tea"|]
Run Code Online (Sandbox Code Playgroud)