here is my code :
let go thriller =
work.ListPos.Clear()
开发者_开发技巧 thriller
work.Thread.Start()
member X.Start() =
work.ListPos.Add <| new Packet( connector.Authorize("admin","1") ) |> go
So it doesn't work. I used wrapper with parameter like this :
let inconnection thriller =
using <| new SqlConnection(insql) <| fun X -> X.Open(); thriller X;
inconnection <| fun X ->
I can't use it this way without parameters because I got no X (parameter) but how to create lambda without parameters ?
Thank you.
Use ()
for an empty lambda parameter list or for an empty body:
fun () -> () // unit -> unit
As far as I can see, you're trying to implement the "hole in the middle" pattern - that is, run some initialization, then run a function specified by the user and then run some cleanup.
As dahlbyk already pointed out, you need to pass your go
operation a function of type unit -> unit
. This can be written like this:
let go thriller =
work.ListPos.Clear()
thriller()
work.Thread.Start()
// Use it like this:
go (fun () ->
work.ListPos.Add(new Packet( connector.Authorize("admin","1"))
)
Aside. Your other example isn't really idiomatic F# code. The using
function can be replaced with a use
keyword, which is significantly easier to use:
let inconnection thriller =
use conn = new SqlConnection(insql)
conn.Open()
thriller conn
inconnection (fun conn -> ...)
More tricky option.
Alternatively, you can also use the use
keyword for other things than disposing of resources like SQL connections. This could make your go
function even nicer (but it depends on your particular case). The idea is that you'll be able to write:
use u = go() // work.ListPos.Clear() gets called here
work.ListPos.Add(new Packet(connector.Authorize("Admin", "1")))
// work.Thread.Start() gets called automatically when 'u' variable goes out of scope
To do this, you need to define go
as a function that returns IDisposable
that performs the cleanup:
let go () =
work.ListPos.Clear()
{ new IDisposable with
member x.Dispose() = work.Thread.Start() }
精彩评论