问题描述
我显然是F#的新手。来自C#,我在使用歧视工会方面遇到困难。
假设在F#中具有以下定义:
type Details =
| ContactDetails of ContactDetail * id: Guid
| Internet of Internet * id: Guid
| PhoneNumbers of PhoneNumber * id: Guid
| Addresses of Address * id: Guid
let contactDetail : ContactDetail = {Name="Contact Detail"; Content="Content for Contact Detail"; Text="here is the contact detail text" }
let internet : Internet = {Name="Internet"; Content="Content for Internet"; Text="here is the internet text" }
let phoneNumber : PhoneNumber = {Name="Phone Number"; Content="Content for phone number"; Text="here is the phone number text" }
let address : Address = {Name="Address"; Content="Content for Address"; Text="here is the Address text" }
let details = [ContactDetails (contactDetail,Guid.NewGuid())
Internet (internet,Guid.NewGuid())
PhoneNumbers (phoneNumber,Guid.NewGuid())
Addresses (address,Guid.NewGuid())
]
type Model = {
Details: Details list
}
我该如何编写包含Model并返回列表中每个项目的ID的函数?
即,例如:
乐趣细节-> detail.id
类型“ Details”未定义字段,构造函数或成员“ id”
TIA
编辑#1:
新型号为:
type Model = { 详细信息:DetailsWithId列表 }
解决方法
“有区别的联盟”中的“有区别的”意味着每个字段定义都被认为是彼此不同的,这就是为什么即使您有一个公共字段也无法直接访问它。
我通常要做的最简单的事情是创建一个扩展函数,以安全地提取该字段。
type Details =
| ContactDetails of ContactDetail * id: Guid
| Internet of Internet * id: Guid
| PhoneNumbers of PhoneNumber * id: Guid
| Addresses of Address * id: Guid
member this.id =
match this with
| ContactDetail(_,id)
| Internet(_,id)
| PhoneNumber(_,id)
| Address(_,id) -> id
另一种选择是以不同的方式构造数据:
type Details =
| ContactDetails of ContactDetail
| Internet of Internet
| PhoneNumbers of PhoneNumber
| Addresses of Address
// Each instance will hold one of ContactDetails,Internet,Phonenumber,and
// each has a common property of ID (the Guid). This way,you simplify your model
type DetailsWithId = DetailsWithId of Details * Guid
另一句话:您对DU的每个成员使用复数形式,但该定义仅允许一项。