Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

f# keyword use and using

I am trying to use System.Data.Sqlite with F#. In C#, I have code like

 using (DbTransaction dbTrans = con.BeginTransaction()) {
     using (SQLiteCommand cmd = con.CreateCommand()) {
         //blahblah
     }
     dbTrans.Commit();
 }

But in F#, when I use the similiar two using above I got error of the type bool is not compatible with the type IDisposable... EDIT I am really sorry for my question. use would work in F# case. I just dont know how to close/delete my quesetions.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To add some details - if you need to explicitly mark the scope where command is valid (to get exactly the same behavior as in your C# example, where cmd id disposed of before calling Commit) you can write:

use dbTrans = con.BeginTransaction()
( use cmd = con.CreateCommand()
  cmd.BlahBlahBlah() )
dbTrans.Commit()

The scope is just a part of expression where the symbol is defined, so you can make it explicit using parentheses.

using is just an F# function that you could use before special syntax using use was added. Just FYI, the syntax looks like this:

using (con.BeginTransaction()) (fun dbTrans ->
  using (con.CreateCommand()) (fun cmd ->
    cmd.BlahBlahBlah() )
dbTrans.Commit() )

Writing the code using use is definitely a better idea (but you can define your functions like using to encapsulate more interesting behavior - e.g. transaction).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...