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

Ali*_*Ali 5 .net c# asp.net clr

从以下选项中哪一个更好

一个使用声明是否足够?

选项1:

using(SqlConnection con = new SqlConnection(constring))
{
   using(SqlCommand cmd = new SqlCommand())
   {
       .........................
       .........................
       .........................
   }
}
Run Code Online (Sandbox Code Playgroud)

选项2:

using(SqlConnection con = new SqlConnection(constring))
{
   SqlCommand cmd = new SqlCommand();
   .........................
   .........................
   .........................
}
Run Code Online (Sandbox Code Playgroud)

Kir*_*oll 15

遵循规则通常最简单,"如果类型实现,IDisposable则使用using构造." 所以我会选择某种形式的选项1.


Luk*_*keH 9

你需要把它们都包起来,虽然你可以让它看起来有点整洁,如果那困扰你!

using (var conn = new SqlConnection(/* ... */))
using (var cmd = new SqlCommand(/* ... */))
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)