枚举 F# 区分联合类型的名称和值,如 Enum.GetValues

Enumerate names and values of an F# Discriminated Union type like Enum.GetValues

首先,我阅读了这篇文章:How to enumerate a discriminated union in F#? 但它并没有真正解决我的问题。

我正在尝试解析一个可区分的联合,获取所有类型,获取它们的名称,然后将它们放入字典中(好吧,不止于此,但这是为了简化示例)

open Microsoft.FSharp.Reflection

type MyDU =
|TypeA
|TypeB

let l = Dictionary<MyDU, string>()    

FSharpType.GetUnionCases typeof<ExchangeList>
|> Seq.iter (fun x ->
    l.[WHAT DO I PUT HERE?] <- x.Name
)

I don't know, from the UnionCaseInfo how to get the actual type to put as a key in my dictionary.

之前,我有一个枚举,所以比较简单:

Enum.GetValues(typeof<MyEnum>)
|> unbox
|> Seq.iter (fun x ->
    l.[x] <- string x

您可以使用 FSharpValue.MakeUnion 函数使用 F# 反射创建 DU 实例:

for x in FSharpType.GetUnionCases typeof<MyDU> do
  l.[FSharpValue.MakeUnion(x, [||]) :?> MyDU] <- x.Name