我收到此错误“Visual Basic 9.0不支持这种lambda表达式”此处“ExecuteWithinTransaction( Sub (con,trans)InsertA(”Al“, con,trans))“当我将鼠标悬停在 Sub
上时我是lambda表达式的新手。任何帮助赞赏。我正在使用VS 2010和.NET 3.5。
Sub Main()
ExecuteWithinTransaction(Sub(con, trans) InsertA("Al", con, trans))
ExecuteWithinTransaction(Sub(con, trans) InsertB("Bert", con, trans))
ExecuteWithinTransaction(Sub(con, trans)
InsertA("Albert", con, trans)
InsertB("Einstein", con, trans)
End Sub)
End Sub
''' <summary>
''' Executes an action within a transaction. handles connection and transaction management
''' </summary>
''' <param name="action">The action to be executed</param>
Sub ExecuteWithinTransaction(ByVal action As Action(Of SqlConnection, SqlTransaction))
Dim connection As SqlConnection = New SqlConnection("CONNECTIONSTRING")
connection.Open()
Try
Dim transaction = connection.BeginTransaction()
Try
action(connection, transaction)
transaction.Commit()
Catch ex As Exception
transaction.Rollback()
Throw 'rethrow exception preserving original stacktrace
End Try
Finally
connection.Close()
End Try
End Sub
Sub InsertA(ByVal name As String, ByVal connection As SqlConnection, ByVal transaction As SqlTransaction)
Dim cmd As SqlCommand = New SqlCommand("INSERT INTO XXX (Name) VALUES (@NAME)", connection, transaction)
cmd.Parameters.AddWithValue("@Name", name)
cmd.ExecuteNonQuery()
End Sub
Sub InsertB(ByVal name As String, ByVal connection As SqlConnection, ByVal transaction As SqlTransaction)
Dim cmd As SqlCommand = New SqlCommand("INSERT INTO YYY (Name) VALUES (@NAME)", connection, transaction)
cmd.Parameters.AddWithValue("@Name", name)
cmd.ExecuteNonQuery()
End Sub
答案 0 :(得分:2)
声明lambda( Sub
s)在VB.NET 2012 +中得到支持。
VB.NET 2010仅支持函数lambdas( Function
s)。
请参阅下面的Ric的评论以获得答案。
如果无法更改FW版本,请解决此问题:以普通的非lambda格式编写小助手潜艇,然后将其作为代理传递给ExecuteWithinTransaction
。
所以你会有
private sub Lambda1 (con as SqlConnection, tran as SqlTransaction)
InsertA("Al", con, tran)
end sub
private sub Lambda2 (con as SqlConnection, tran as SqlTransaction)
InsertB("Bert", con, tran)
end sub
private sub Lambda3 (con as SqlConnection, tran as SqlTransaction)
InsertA("Albert", con, tran)
InsertB("Einstein", con, tran)
end sub
然后
ExecuteWithinTransaction (AddressOf Lambda1)
ExecuteWithinTransaction (AddressOf Lambda2)
ExecuteWithinTransaction (AddressOf Lambda3)