如何枚举F#中的枚举/类型

Jar*_*red 13 .net enums f#

我有一个像这样定义的枚举类型:

type tags = 
    | ART  = 0
    | N    = 1
    | V    = 2 
    | P    = 3
    | NULL = 4
Run Code Online (Sandbox Code Playgroud)

有办法for ... in tags do吗?

这是我得到的错误:

tags未定义值,构造函数,命名空间或类型

jas*_*son 8

用途Enum.GetValues:

let allTags = Enum.GetValues(typeof<tags>)
Run Code Online (Sandbox Code Playgroud)

  • 我的问题是GetValues将返回一个数组,我不能让它回到枚举.我试过`enum <tags> tag`但是没用. (2认同)

Tom*_*cek 6

这是一个完整的示例,打印有关任何歧视联合的信息.它显示了如何获得歧视联合的案例以及如何获取字段(如果您需要它们).该函数打印给定的区分联合的类型声明:

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)

  • 帖子中的原始类型声明(在你编辑之前)是一个有区别的联盟,但是...枚举当然在F#中也很有用,但只在少数几种情况下. (2认同)

小智 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)