繁体   English   中英

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

[英]Syntax: In F# how to return a value from a member of a discriminated union?

使用以下代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM