F# 联合成员的 Enum.GetName 等效项是什么? [英] What is the Enum.GetName equivalent for F# union member?
本文介绍了F# 联合成员的 Enum.GetName 等效项是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为 F# 受歧视的联合成员获得等效的 Enum.GetName
.调用 ToString()
给了我 TypeName+MemberName,这不是我想要的.当然,我可以将它子串起来,但是它安全吗?或者也许有更好的方法?
I want to get the equivalent of Enum.GetName
for an F# discriminated union member. Calling ToString()
gives me TypeName+MemberName, which isn't exactly what I want. I could substring it, of course, but is it safe? Or perhaps there's a better way?
推荐答案
您需要使用 Microsoft.FSharp.Reflection
命名空间中的类,因此:
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<Beverage>()
> val it : string array = [|"Coffee"; "Tea"|]
这篇关于F# 联合成员的 Enum.GetName 等效项是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文