2013-09-28 21 views
2

对于C#我还是比较陌生,并且只在过去的几天内才暴露给“IDisposables”。我可以掌握using块的概念,以照顾必须处理的物体,而无需手动记住拨打.Dispose()方法 - 方便!在另一个IDisposable中处理IDisposables“使用”语句

让我们假设,虽然我从一个新的SqlConnection开始,我在using声明中处理。在该代码块中,我创建了一些额外的IDisposables,例如SqlDataAdapter。该适配器是否需要它自己的using声明?

例如,如果我有代码...

using (SqlConnection myConnection = new SqlConnection()) 
{ 
    SqlCommand myCommand = new SqlCommand(); 
    SqlDataAdapter myAdapter = new SqlDataAdapter(); 
    // Do things 
} 

...将myCommandmyAdapter被设置时myConnection设置的(因为它们是代码块的范围内的)?或者我需要多using语句,也许是这样的:using语句

using (SqlConnection myConnection = new SqlConnection()) 
{ 
    using (SqlCommand myCommand = new SqlCommand()) 
    { 
     using (SqlDataAdapter myAdapter = new SqlDataAdapter()) 
     { 
      // Do things 
     } 
    } 
} 
+1

是你使用块,使每个对象处理函数被调用需要多个在使用块结束的范围。 – dbw

+1

请注意,需要记住Dispose()只是需要记住'using(){}'。主要的优点是可读性和异常安全性。 –

回答

7

严格地说嵌套语法糖,它确实是最好的处置所有其中。但是,您可以通过直接嵌套他们避免缩进:

using (var myConnection = new SqlConnection()) 
using (var myCommand = new SqlCommand()) 
using (var myAdapter = new SqlDataAdapter()) 
{ 
    // Do things 
} 

另外,特别是在ADO.NET的情况下(这不,让我们的是公平的,有很多一次性类型的),你可能会发现更容易使用该隐藏了很多管道的图书馆之一 - 例如,与“短小精悍”:

using(var conn = new SqlConnection(...)) 
{ 
    return conn.Query<Customer>(
     "select * from Customers where [email protected]", 
     new { region }).ToList(); 
} 
3

这是否适配器需要它自己的?

在这种情况下,没有。但是,这取决于连接和适配器对象的详细知识,例如最佳实践:使用一个using()IDisposable。即使对于MemoryStream Dispose()什么都不做。它们便宜。

你的代码是正确的,但我们平时节约的{}

using (SqlConnection myConnection = new SqlConnection()) 
using (SqlCommand myCommand = new SqlCommand())  
using (SqlDataAdapter myAdapter = new SqlDataAdapter()) 
{ 
    // Do things 
} 

我们在这里使用的规则,当一个using()控制1个语句(下一using()),你不需要花括号。然后我们对缩进进行一点修改。

0

使用仅仅是

  var connection = new Connection(); 
     try 
     { 
      connection.DoSomething(); 
     } 
     finally 
     { 
      // Check for a null resource. 
      if (connection != null) 
      { 
       ((IDisposable)connection).Dispose(); 
      } 
     } 

所以,是的,您需要使用语句一定要处理所有这些

相关问题