语法:在F#中,如何从已区分联合的成员返回值?

问题描述

使用以下代码

type ContactDetail = { Name: string; Content: string; Text: string }
type Internet      = { Name: string; Content: string; Text: string }
type PhoneNumber   = { Name: string; Content: string; Text: string }
type Address       = { Name: string; Content: string; Text: string }

    module FrontOffice =    
        type Details =
            | ContactDetail of ContactDetail * Id: Guid
            | Internet      of Internet   * Id: Guid
            | PhoneNumber   of PhoneNumber   * Id: Guid
            | Address       of Address  * Id: Guid
            
          
            member this.name = 
                match this with
                | ContactDetail(_,id)
                | Internet(_,id) 
                | PhoneNumber(_,id) 
                | Address(_,id) -> ???????????????????

我需要扩展方法this.name来返回匹配项的Name属性。怎么做?

TIA

解决方法

方法如下:

type ContactDetail = { Name: string; Content: string; Text: string }
type Internet      = { Name: string; Content: string; Text: string }
type PhoneNumber   = { Name: string; Content: string; Text: string }
type Address       = { Name: string; Content: string; Text: string }

module FrontOffice =

    type Details =
        | ContactDetail of ContactDetail * Id: Guid
        | Internet      of Internet   * Id: Guid
        | PhoneNumber   of PhoneNumber   * Id: Guid
        | Address       of Address  * Id: Guid
        
        member this.name = 
            match this with
            | ContactDetail (cd,_) -> cd.Name
            | Internet (i,_) -> i.Name
            | PhoneNumber (pn,_) -> pn.Name
            | Address (a,_) -> a.Name

    let sample () =
        let contactDetail = { ContactDetail.Name = "myname"; Content = "mycontent"; Text = "mytext" }
        let details: Details = ContactDetail (contactDetail,Guid.NewGuid ())
        printfn "%A" details
        // ContactDetail ({Name = "myname"; Content = "mycontent"; Text = "mytext";},1a25bcdd-76b0-4cb3-8a34-72872d2542c2)
        printfn "The name is %s" details.name
        // The name is myname