多重使用c#块

本文关键字: | 更新日期: 2023-09-27 17:49:33

我正在工作的应用程序,我需要访问数据库。使用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.所以我有点困惑在哪里使用"using",在哪里不使用。

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)
    {
    }
}

多重使用c#块

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

using块语法糖(相对于手动.Dispose()调用)的好处是,即使出现异常并且流离开using块,Dispose()仍然会被调用。

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

using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand com = new SqlCommand("",con))
using (SqlDataReader sdr = com.ExecuteReader()) // Still need to open connection ...
{
   ...
另外,using的另一个好处是,如果在using中声明了IDisposable变量,则该变量为readonly,并且不能在块中重新分配,例如:
using (SqlDataReader sdr = com.ExecuteReader())
{
   sdr = new SqlDataReader() // Error

可以这样简化:

using (SqlConnection con = new SqlConnection(connectionString))
using(SqlCommand com = new SqlCommand("",con))
using (SqlDataReader sdr = com.ExecuteReader())
{
     ...
}

Using语句被翻译成try/finally块。因此,即使抛出异常,您的对象也将是Disposed。因此,如果您有一个Disposable对象,并且您想确保它在使用后将被处置,您可以使用using语句。记住这是一种语法糖:

SqlCommand cmd;
try
{
    cmd = new SqlCommand();
    ...
}
finally
{
   ((IDisposable)cmd).Dispose();
}

using块而言,这看起来不错。

然而,你不应该在这里使用try/catch块,除非你打算实际处理异常。否则你只是隐藏了可能的错误,这是绝对错误的。
相关文章:
  • 没有找到相关文章