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

后端 未结 3 1124
难免孤独
难免孤独 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:37

    You need to use the classes in the Microsoft.FSharp.Reflection namespace so:

    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()
    > val it : string array = [|"Coffee"; "Tea"|]
    

提交回复
热议问题