我编写了很多利用 Entity Framework 和 LINQ 返回 JSON 数据的 VB.net Web 服务。很多时候我只是直接从 Using 语句中返回数据。
我不禁想知道,存储返回值并在 Using 语句之外返回它有什么好处吗?
MSDN documentation on Using状态:
" the Using block guarantees disposal of the resources, no matter how you exit the block. "
所以我认为这同样可以接受,但我只是想确保我没有遗漏任何潜在的问题。
示例代码:
<WebMethod(), ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Function GetListOfRows()
Try
Using CTX As New [EFContext]
Return (
From R In CTX.[Rows]
).ToList()
End Using
Catch Ex As Exception
'Capture & Report Error
End Try
End Function
最佳答案
我会说在 using 语句中返回是可以接受的。请记住,using 是一个 try-catch-finally,在 using 中运行代码后,它将像 finally 一样调用 dispose 方法。这将与您的代码相同:
Try
Return (From R In CTX.[Rows]).ToList
Catch Ex As Exception
'Capture & Report Error
Finally
'dispose
End Try
关于.net - Return 语句是否会对 Using block 产生负面影响?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19569935/