我有一个像这样定义的枚举类型:
type tags =
| ART = 0
| N = 1
| V = 2
| P = 3
| NULL = 4
Run Code Online (Sandbox Code Playgroud)
有办法for ... in tags do吗?
这是我得到的错误:
tags未定义值,构造函数,命名空间或类型
let allTags = Enum.GetValues(typeof<tags>)
Run Code Online (Sandbox Code Playgroud)
这是一个完整的示例,打印有关任何歧视联合的信息.它显示了如何获得歧视联合的案例以及如何获取字段(如果您需要它们).该函数打印给定的区分联合的类型声明:
open System
open Microsoft.FSharp.Reflection
let printUnionInfo (typ:Type) =
printfn "type %s =" typ.Name
// For all discriminated union cases
for case in FSharpType.GetUnionCases(typ) do
printf " | %s" case.Name
let flds = case.GetFields()
// If there are any fields, print field infos
if flds.Length > 0 then
// Concatenate names of types of the fields
let args = String.concat " * " [ for fld in flds -> fld.PropertyType.Name ]
printf " of %s" args
printfn ""
// Example
printUnionInfo(typeof<option<int>>)
Run Code Online (Sandbox Code Playgroud)
小智 6
怎么样:
let enumToList<'a> = (Enum.GetValues(typeof<'a>) :?> ('a [])) |> Array.toList
Run Code Online (Sandbox Code Playgroud)
这具有提供强类型列表的优点
要使用,只需执行以下操作:
let tagList = enumToList<tags>
Run Code Online (Sandbox Code Playgroud)