这是我的问题的延续F# 联合类型列表 https://stackoverflow.com/questions/13770911/f-list-of-union-types。感谢有用的反馈,我能够创建一个列表Report
s, with Report
要么是Detail
or Summary
。这是数据定义:
module Data
type Section = { Header: string;
Lines: string list;
Total: string }
type Detail = { State: string;
Divisions: string list;
Sections: Section list }
type Summary = { State: string;
Office: string;
Sections: Section list }
type Report = Detail of Detail | Summary of Summary
现在我已经得到了名单Report
s 在一个名为的变量中reports
,我想迭代那些Report
对象并基于每个对象执行操作。除了处理任一情况外,操作都是相同的Detail.Divisions
or Summary.Office
。显然,我必须以不同的方式处理这些问题。但我不想重复处理类似的所有代码State
and Sections
每个。
我的第一个(工作)想法如下:
for report in reports do
let mutable isDetail = false
let mutable isSummary = false
match report with
| Detail _ -> isDetail <- true
| Summary _ -> isSummary <- true
...
这将使我知道何时处理Detail.Divisions
而不是Summary.Office
。但它并没有给我一个可以使用的对象。我仍然坚持report
,不知道它是什么,Detail
or Summary
,并且也无法访问属性。我想转换report
到适当的Detail
or Summary
然后使用相同的代码来处理任一情况,但以下情况除外Detail.Divisions
and Summary.Office
。有没有办法做到这一点?
Thanks.
你可以这样做:
for report in reports do
match report with
| Detail { State = s; Sections = l }
| Summary { State = s; Sections = l } ->
// common processing for state and sections (using bound identifiers s and l)
match report with
| Detail { Divisions = l } ->
// unique processing for divisions
| Summary { Office = o } ->
// unique processing for office
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)