2011-02-11 67 views
14

我想用F#使用System.Data.Sqlite。在C#中,我有一個像f#關鍵字的使用和使用

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

但在F#代碼,當我使用similiar 2 using上面我的the type bool is not compatible with the type IDisposable錯誤... 編輯我爲我的問題真的很抱歉。 use將在F#的情況下工作。我只是不知道如何關閉/刪除我的quesetions。

+4

我不知道你是否真的需要刪除這個問題。這不是一個壞問題:它得到了讚賞,還有兩個體面的答案。 – Benjol 2011-02-14 06:40:29

回答

8
在F#

use dbTrans = new con.BeginTransaction() 

use cmd = con.CreateCommand() 

當你的函數結束

15

要添加一些細節,這些將部署 - 如果你需要一個命令是有效的顯式標記範圍(以獲得與您的C#示例中完全相同的行爲,其中cmd id在致電Commit之前已處理),您可以編寫:

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

範圍只是表達式中定義符號的一部分,因此您可以使用圓括號將其顯式化。

using只是一個F#函數,您可以在添加特殊語法之前使用use。僅供參考,語法如下:

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

寫的用use絕對是一個更好的主意代碼(但是你可以這樣定義using的功能封裝更有趣的行爲 - 例如交易)。