如何在多个实例中使用Using语句?

时间:2013-01-08 07:39:36

标签: c# asp.net c#-4.0

我想使用using SqlConnectionSqlCommand个对象来处置它们。我如何在这种情况下使用?

例如:

using (sqlConnection = new SqlConnection(IRLConfigurationManager.GetConnectionString("connectionStringIRL")))
{
}

但是我在这里使用基于if条件的连接。

SqlConnection _sqlConnection;
SqlCommand sqlCmd;
DBPersister per = (DBPersister)invoice;
if (per == null)
{
    _sqlConnection = new SqlConnection(IRLConfigurationManager.GetConnectionString("connectionStringIRL"));
    sqlCmd = new SqlCommand("usp_UpdateDocumentStatusInImages", _sqlConnection);
}
else
{
    _sqlConnection = per.GetConnection();
    sqlCmd = per.GenerateCommand("usp_UpdateDocumentStatusInImages", _sqlConnection, per);
}

sqlCmd.CommandType = CommandType.StoredProcedure;
//mycode

try
{
    if (_sqlConnection.State == ConnectionState.Closed)
        _sqlConnection.Open();
    sqlCmd.ExecuteNonQuery();
}
catch
{
    throw;
}
finally
{
    if (per == null)
        invoice._sqlConnection.Close();
}

2 个答案:

答案 0 :(得分:4)

您可以嵌套它们,如下所示:

using (var _sqlConnection = new SqlConnection(...))
{
    using (var sqlCmd = new SqlCommand(...))
    {
        //code
    }
}

答案 1 :(得分:1)

使用conditional运算符确定要为每个变量分配的内容:

using(SqlConnection _sqlConnection = per==null?
      new SqlConnection(IRLConfigurationManager.GetConnectionString("connectionStringIRL"))
      : per.GetConnection())
using(SqlCommand sqlCmd = per==null?
      new SqlCommand("usp_UpdateDocumentStatusInImages", _sqlConnection);
      : per.GenerateCommand("usp_UpdateDocumentStatusInImages", 
       _sqlConnection, per))
{
  //Code here using command and connection
}

虽然我必须说,per.GenerateCommand(..., per)看起来像一个奇怪的函数(它是一个实例方法,也必须传递一个同一个类的实例 - 它必须始终是同一个实例吗?)