C# 如何对多个实例使用Using语句?
我想对C# 如何对多个实例使用Using语句?,c#,asp.net,c#-4.0,C#,Asp.net,C# 4.0,我想对SqlConnection和SqlCommand对象使用using来处理这些对象。在这种情况下我如何使用 例如: using (sqlConnection = new SqlConnection(IRLConfigurationManager.GetConnectionString("connectionStringIRL"))) { } 但这里我使用的是基于if条件的连接 SqlConnection _sqlConnection; SqlCommand sqlCmd; DBPersis
SqlConnection
和SqlCommand
对象使用using
来处理这些对象。在这种情况下我如何使用
例如:
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(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)
看起来像是一个奇怪的函数(它是一个实例方法,也必须传递给同一类的实例-它必须始终是同一个实例吗?使用操作符来确定分配给每个变量的内容:
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)
看起来像一个奇怪的函数(它是一个实例方法,也必须传递一个相同类的实例-它必须始终是相同的实例吗?您可以嵌套它们,如下所示:
using (var _sqlConnection = new SqlConnection(...))
{
using (var sqlCmd = new SqlCommand(...))
{
//code
}
}
您可以将其嵌套,如下所示:
using (var _sqlConnection = new SqlConnection(...))
{
using (var sqlCmd = new SqlCommand(...))
{
//code
}
}
我猜您被限制为使用的单个
的类型我猜您被限制为使用
的单个的类型,如果您跳过{}和缩进,它们甚至更可读-我完全支持{},但我的编码标准对使用语句链接有特殊的概念;)这看起来很有逻辑,而且看起来vs不会自动缩进第二次使用。为什么以前没有人告诉我这个?如果你跳过{}和缩进,它们甚至更可读——我完全支持{},但我的编码标准有使用语句链接的特殊概念;)这看起来很有逻辑,而且看起来vs不会自动缩进第二次使用。为什么以前没人告诉我?