多个使用块c#

Hot*_*tud 2 .net c# asp.net using using-statement

我正在处理我需要访问数据库的应用程序.使用using语句很好,因为"using" statement is to ensure that the object is always disposed correctly, and it doesn't require explicit code to ensure that this happens.我有点困惑在哪里使用"使用",哪里不使用.

public int route(Route r)
{
    try
    {
        using (SqlConnection con = new SqlConnection(connectionString))
        {
            using(SqlCommand com = new SqlCommand("",con))
            {
                using (SqlDataReader sdr = com.ExecuteReader())
                {
                }
            }
        }
    }
    catch (Exception e)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

Stu*_*tLC 9

任何时候你创建的对象实现IDisposable,处理它(有或没有using语法糖)是一个好主意.

在的好处using块语法糖(比手动.Dispose()调用)是Dispose()仍然被调用,即使有异常和流量离开using块.

另请注意,您可以堆叠使用,而不使用嵌套缩进:

using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand com = new SqlCommand("",con))
using (SqlDataReader sdr = com.ExecuteReader()) // Still need to open connection ...
{
   ...
Run Code Online (Sandbox Code Playgroud)

顺便说一句,另一个好处using是,如果IDisposable变量是在变量中声明的using,那么变量是否readonly在块内重新分配,例如:

using (SqlDataReader sdr = com.ExecuteReader())
{
   sdr = new SqlDataReader() // Error
Run Code Online (Sandbox Code Playgroud)

  • @HotCoolStud不worry.Compiler会的that.It是足够聪明,知道你是想嵌套语句,这就是为什么它是一个有效的语法照顾. (2认同)