Domanda

Voglio ottenere l'equivalente di Enum.GetName per un F # discriminati sindacalista. Chiamata ToString() mi dà TypeName + MemberName, che non è esattamente quello che voglio. Potrei sottostringa che, naturalmente, ma è sicuro? O forse c'è un modo migliore?

È stato utile?

Soluzione

È necessario utilizzare le classi nello spazio dei nomi Microsoft.FSharp.Reflection modo:

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"|]

Altri suggerimenti

@ risposta di DanielAsher funziona, ma per renderlo più elegante, vorrei farlo in questo modo (e veloce a causa della mancanza di riflessione per uno dei metodi?):

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

(Ispirato da questo e questo .)

Vorrei proporre qualcosa di ancora più conciso:

open Microsoft.FSharp.Reflection

type Coffee = { Country: string; Intensity: int }

type Beverage =
    | Tea
    | Coffee of Coffee

    member x.GetName() = 
        match FSharpValue.GetUnionFields(x, x.GetType()) with
        | (case, _) -> case.Name  

Quando caso l'unione è semplice, GetName() può portare lo stesso ToString():

> let tea = Tea
val tea : Beverage = Tea

> tea.GetName()
val it : string = "Tea"

> tea.ToString()
val it : string = "Tea"

Tuttavia, se caso unione è più elaborato, ci sarà una differenza :.

> let coffee = Coffee ({ Country = "Kenya"; Intensity = 42 })
val coffee : Beverage = Coffee {Country = "Kenya"; Intensity = 42;}

> coffee.GetName()
val it : string = "Coffee"

> coffee.ToString()
val it : string = "Coffee {Country = "Kenya";        Intensity = 42;}"
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top