如何为多个实例使用Using语句

本文关键字:Using 语句 实例 | 更新日期: 2023-09-27 17:50:55

我想使用usingSqlConnectionSqlCommand对象来处理这些。在这种情况下如何使用?

例如:

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();
}

如何为多个实例使用Using语句

你可以嵌套它们,像这样:

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

使用条件运算符确定每个变量的赋值:

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)看起来像一个奇怪的函数(它是一个实例方法,也必须传递同一个类的实例-它必须总是相同的实例吗?)