我正在尝试从字符串创建DU案例.我可以看到这样做的唯一方法是通过枚举DU情况Microsoft.FSharp.Reflection.FSharpType.GetUnionCases,然后选择UnionCase匹配字符串(通过使用.Name),然后通过使用实现DU的情况FSharpValue.MakeUnion.
这样做是不是更简单/更优雅?在我的场景中,我有一个DU,有几百个关键字案例.我必须从文件中读取字符串(关键字)并从中提取类型.通过将案例放入Map中我做了一些"优化",但我希望有更好的方法来做到这一点.
我有以下内容,例如:
type Keyword =
| FOO
| BAR
| BAZ
| BLAH
let mkKeywords (file: string) =
use sr = new StreamReader(file)
let caseMap =
FSharpType.GetUnionCases(typeof<Keyword>)
|> Array.map (fun c -> (c.Name, FSharpValue.MakeUnion(c, [||]) :?> Keyword))
|> Map.ofArray
[
while not sr.EndOfStream do
let l = sr.ReadLine().Trim()
match caseMap.TryFind l with
| Some c -> yield c
| None -> failwith <| "Could not find keyword: " + l
]
Run Code Online (Sandbox Code Playgroud)