语法:在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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...