using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
}
}
见天看了别人的源码!不知道为什么要这样写!这样写的好处是什么呢?

解决方案 »

  1.   

    就是代码块中无论有异常,都会执行相应的Dispose()方法,释放资源。
    在不需要获得异常信息时,比try catch finnally方便。
      

  2.   


                using(SqlConnection SqlConn = new SqlConnection(SqlConnStr))
                {
                    using(DataSet ds = new DataSet())
                    {
                        using(SqlCommand cmd = new SqlCommand(QueryStr, SqlConn))
                        {
                            using(SqlDataAdapter sda = new SqlDataAdapter(cmd))
                            {
                                sda.Fill(ds);
                                return ds.Tables[0];
                            }
                        }
                    }
                }
    那我这样写也行吗?
    还是不需要写多这么多!
      

  3.   

    如果一个类,有Close方法和Dispose方法,就可以用using
    如果仅有Dispose方法,一般没必要用using所以只要对Connection用using就行了,其他没必要的。
      

  4.   

    那么,关闭了sqlconnection sqlcommand也会自动dispose吗?
      

  5.   

    不会,SqlCommand没必要手动执行Dispose方法,垃圾回收会自动处理的。