.net - Return 语句是否会对 Using block 产生负面影响?

标签 .net vb.net linq entity-framework linq-to-entities

我编写了很多利用 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/

相关文章:

vb.net - 如何在 VB.NET 中使用 "Into"LINQ 表达式?

linq - 平面列表到层次结构

c# - LINQ 从多行条件中选择一个 bool 值

c# - 将 MYSQL 数据库中的数据显示到控件,尤其是在 DropDown 的 Combobox 上

c# - 在 C# 中将 COM 对象作为参数传递

VB.NET CheckedListBox 标签?

c# - 获取List <string>中字符串的索引

c# - 合并键值对列表

c# - 在方法中声明类或结构

c# - 实现 INotifyPropertyChanged - 是否存在更好的方法?