`use`关键字不适用于咖喱形式?

col*_*ang 1 f#

let make f =
  printfn "1"
  use file = File.CreateText("abc.txt")
  let v = f file
  printfn "2"
  v

let f (x: StreamWriter) (y:int) = 
  printfn "3"
  x.WriteLine("{0}", y)

let a = make f

> 1
> 2
> val a : (int -> unit)

a 8

System.ObjectDisposedException: The object was used after being disposed.
Run Code Online (Sandbox Code Playgroud)

编译时没有给我任何错误或警告,但在运行时它会触发这样的错误.

我是否必须使用完整版本let make f y = ...以避免咖喱形式?

Tom*_*cek 6

use关键字确保Dispose方法被调用在词法作用域的末尾.这意味着它在从make函数返回值时调用它.问题是,在您的情况下,返回的值是稍后调用的函数.

换句话说,你写的东西也可以看作:

let make f =
  printfn "1"
  use file = File.CreateText("abc.txt")
  printfn "2"
  (fun y -> f file y)
Run Code Online (Sandbox Code Playgroud)

在这里,您可以看到为什么这不起作用.如果要f在处理文件之前使用所有参数调用该函数,则需要编写如下内容:

let make f y =
  printfn "1"
  use file = File.CreateText("abc.txt")
  let v = f file y
  printfn "2"
  v
Run Code Online (Sandbox Code Playgroud)