情况:一个函数返回一个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"
答案 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"