C#.net中的using语法,using (SqlCommand cmd = new SqlCommand(SQLString, connection))
public static int ExecuteSql(string SQLString) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(SQLString, connection)) { try { connection.Open(); int rows = cmd.ExecuteNonQuery(); return rows; } catch (System.Data.SqlClient.SqlException e) { connection.Close(); throw e; } finally { cmd.Dispose(); connection.Close(); } } } } 其中using (SqlCommand cmd = new SqlCommand(SQLString, connection))这句为什么要这样写呢?直接写SqlCommand cmd = new SqlCommand(SQLString, connection不就可以了吗? 为什么还要用using()包围呀,这样写有什么好处吗? 最好能引用微软官方解释。
满意回答
1. 如果你需要使用一个对象,这个对象需要占用很多紧缺的资源,使用完成后需要马上释放掉的话,建议使用using语句 2. 这样写是为了避免资源释放不及时导致的冲突或性能问题 3. 这样写的话处是减少因为争抢资源发生冲突或性能问题的概率 4. 以下为微软官方关于using语句的解释 提供能确保正确使用 IDisposable 对象的方便语法。 语法 复制代码 using (Font font1 = new Font("Arial", 10.0f)) { .. byte charset = font1.GdiCharSet; } 备注 File 和 Font 是访问非托管资源(本例中为文件句柄和设备上下文)的托管类型的示例。有许多其他类别的非托管资源和封装这些资源的类库类型。所有这些类型都必须实现 IDisposable 接口。 按照规则,当使用 IDisposable 对象时,应在 using 语句中声明和实例化此对象。using 语句按照正确的方式调用对象上的 Dispose 方法,并(在您按照前面所示方式使用它时)会导致在调用 Dispose 时对象自身处于范围之外。在 using 块中,对象是只读的并且无法进行修改或重新分配。 using 语句确保调用 Dispose,即使在调用对象上的方法时发生异常也是如此。通过将对象放入 try 块中,并在调用 finally 块中的 Dispose,可以获得相同的结果;实际上,这就是编译器转换 using 语句的方式。前面的代码示例在编译时将扩展到以下代码(请注意,使用额外的大括号为对象创建有限范围): { 复制代码 Font font1 = new Font("Arial", 10.0f); try { byte charset = font1.GdiCharSet; } finally { if (font1 != null) ((IDisposable)font1).Dispose(); } } 可以将多个对象与 using 语句一起使用,但必须在 using 语句中声明这些对象,如以下示例所示: 复制代码 using (Font font3 = new Font("Arial", 10.0f), font4 = new Font("Arial", 10.0f)) { // Use font3 and font4. } 可以实例化资源对象,然后将变量传递给 using 语句,但这不是最佳做法。在这种情况下,该对象将在控制权离开 using 块之后保持在范围内,即使它可能将不再具有对其非托管资源的访问权也是如此。换句话说,再也不能完全初始化该对象。如果试图在 using 块外部使用该对象,则可能导致引发异常。由于这个原因,通常最好是在 using 语句中实例化该对象并将其范围限制在 using 块中。 复制代码 Font font2 = new Font("Arial", 10.0f); using (font2) // not recommended { // use font2 } // font2 is still in scope // but the method call throws an exception float f = font2.GetHeight();