对作为选项返回的一次性对象使用样式绑定

san*_*tel 7 f#

想知道是否有一种优雅的方式来完成以下任务:

我有一个创建Disposable的函数并将其作为选项返回.呼叫者匹配它.现在,由于包装对象被绑定到匹配大小写内部,我不知道如何在匹配内部进行"使用"样式绑定,以便正确处理对象.

let createSocket (hostEntry:IPHostEntry) =
    let httpPort = 80
    let endpoint = new IPEndPoint(hostEntry.AddressList.[0], httpPort)
    let socket = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
    socket.Connect(endpoint)
    if (socket.Connected) then Some socket else None

let fetchResource url =
    let uri = new System.Uri(url)
    let hostEntry = Dns.GetHostEntry(uri.Host)
    match createSocket(hostEntry) with
    | Some socket ->
        use s = socket // More elegant way?
        sendRequest s uri.Host uri.PathAndQuery |> getResponse
    | None ->
        "Failed to open socket"
Run Code Online (Sandbox Code Playgroud)

scr*_*wtp 6

你有一个using核心库中可用的功能,但你是否认为这更优雅取决于你:

match createSocket(hostEntry) with
| Some socket ->
    using socket <| fun s ->
        sendRequest s uri.Host uri.PathAndQuery |> getResponse
| None ->
    "Failed to open socket"
Run Code Online (Sandbox Code Playgroud)

您可以更进一步,将整个技巧打包在一个函数中:

module Option =     
    let using func = Option.bind (fun disp -> using disp func)

...

createSocket(hostEntry)
|> Option.using (fun s ->
    sendRequest s uri.Host uri.PathAndQuery |> getResponse)
// handle None however you like
|> function Some x -> x | None -> "Failed to open socket" 
Run Code Online (Sandbox Code Playgroud)

虽然我不记得我曾经觉得有必要亲自这样做.