如何在匹配模式中使用“使用”声明?

时间:2013-09-08 16:06:00

标签: f# pattern-matching idisposable

情况:一个函数返回一个Option(Stream)。在调用函数中,我必须以某种方式展开它,以便在使用后丢弃流。我应该把“使用”声明放在哪里?

let getSteamOpt = if System.Random().NextDouble() > 0.5 then Some(new MemoryStream()) else None
let createAndUseStreamIfAny = 
    let streamOpt = getSteamOpt
    match streamOpt with
    | Some( (* use <-- doesn't work like this *) stream) -> printf "stream has to be disposed after this"
    | None -> printf "blah"

1 个答案:

答案 0 :(得分:3)

let createAndUseStreamIfAny = 
    let streamOpt = getSteamOpt
    match streamOpt with
    | Some(s) -> 
        use stream = s
        printf "stream has to be disposed after this"
    | None -> printf "blah"