问题描述
如何枚举 F# 中可区分联合的可能值"?
How can I enumerate through the possible "values" of a discriminated union in F#?
我想知道是否有类似 Enum.GetValues(Type)
之类的用于区分联合的东西,我不确定我会枚举什么样的数据.我想为每个选项生成一个可区分联合的列表或数组.
I want to know if is there something like Enum.GetValues(Type)
for discriminated unions, tough I am not sure over what kind of data I would enumerate. I would like to generate a list or array of a discriminated union with one item for each option.
推荐答案
是的,F# 有它自己的反射层构建在 .NET 的反射之上,以帮助您理解特定于 F# 的类型,例如区分联合.这是让您枚举联合案例的代码:
Yes, F# has it's own reflection layer build on top of .NET's reflection to help you make sense of types that are specific to F#, like discriminating unions. Here's the code that will let you enumerate a union's cases:
open Microsoft.FSharp.Reflection
type MyDU =
| One
| Two
| Three
let cases = FSharpType.GetUnionCases typeof<MyDU>
for case in cases do printfn "%s" case.Name
这篇关于如何在 F# 中枚举受歧视的联合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!