C#使用关键字,正确使用

C#使用关键字,正确使用,c#,asp.net,.net,clr,C#,Asp.net,.net,Clr,以下选项中哪一个更好 一个使用语句就足够了吗 选项1: using(SqlConnection con = new SqlConnection(constring)) { using(SqlCommand cmd = new SqlCommand()) { ......................... ......................... ......................... } } using(Sq

以下选项中哪一个更好

一个使用语句就足够了吗

选项1:

using(SqlConnection con = new SqlConnection(constring))
{
   using(SqlCommand cmd = new SqlCommand())
   {
       .........................
       .........................
       .........................
   }
}
using(SqlConnection con = new SqlConnection(constring))
{
   SqlCommand cmd = new SqlCommand();
   .........................
   .........................
   .........................
}
选项2:

using(SqlConnection con = new SqlConnection(constring))
{
   using(SqlCommand cmd = new SqlCommand())
   {
       .........................
       .........................
       .........................
   }
}
using(SqlConnection con = new SqlConnection(constring))
{
   SqlCommand cmd = new SqlCommand();
   .........................
   .........................
   .........................
}

一般来说,遵循规则是最简单的,“如果类型实现了
IDisposable
,那么就使用
使用
构造。”因此,我会选择某种形式的选项1。

不,这是不够的,根据经验,每次实例化IDisposable时,都要用using块括起来。

最好使用两个using命令(尽管有)当您有多个时。垃圾收集最好明确说明您希望何时访问这些资源。

第一个肯定更好

即使当连接和命令之间存在一种关系,使得外部的关系足够时,你也不想依赖它,或者期望你的读者知道


而且这种关系永远不会被记录下来,并且可能会在未来的版本中发生变化。

您需要将它们都包装起来,尽管如果这让您感到困扰,您可以让它看起来稍微整洁一点

using (var conn = new SqlConnection(/* ... */))
using (var cmd = new SqlCommand(/* ... */))
{
    // ...
}

是什么让你认为
IDisposable
使用(…)
与垃圾收集器有关吗?@asawyer在这两种情况下,我猜我们都在处理清除内存的问题。即使连接和命令之间存在关系,您是否会澄清
的可能重复。谢谢命令需要连接,当您关闭连接时,您永远不会保留服务上的资源虽然连接池可能会让它变得不那么清晰。另请参见TextReader和Stream。