开发者

scope of 'use' keyword using F#

开发者 https://www.devze.com 2023-03-12 13:09 出处:网络
Assume the following code: let fn () = use a = new System.IO.StreamWriter (\"d:\\\\test.txt\") a let b = fn 开发者_如何转开发()

Assume the following code:

let fn () =
  use a = new System.IO.StreamWriter ("d:\\test.txt")
  a

let b = fn 开发者_如何转开发()
b.Write "t"

It gives following error:

ObjectDisposedException: Cannot write to a closed TextWriter.

Why is that?


use is scoped to the function fn so when a is returned it also disposed.

The easiest way to cure this is:

let fn () =
  let a = new System.IO.StreamWriter ("d:\\test.txt")
  a

let main() = 
  use b = fn ()
  b.Write "t"
main()


To add a bit more to Robert's (correct) answer: you can achieve even finer control over the scope of use with scoping constructs (parentheses or begin/end). See Brian's answer to a related question.


The resource will be disposed as soon as the variable (in your case a) goes out of scope.

This means that after the call to fn the StreamWriter will already be disposed.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号