如果您使用 using 子句来处理连接,子句中实现 IDisposable 的其他项目是否也会自动处理?如果没有,您如何处理以确保自动处理所有 IDisposable 项目?
public static DataTable ReturnDataTable(
string ConnectionString, string CommandTextString, CommandType CommandType,
int CommandTimeout, List<System.Data.SqlClient.SqlParameter> ParameterList = null)
{
using (System.Data.SqlClient.SqlConnection Connection =
new System.Data.SqlClient.SqlConnection())
{
Connection.ConnectionString = ConnectionString;
System.Data.SqlClient.SqlCommand Command =
new System.Data.SqlClient.SqlCommand();
Command.Connection = Connection;
Command.CommandText = CommandTextString;
Command.CommandType = CommandType;
Command.CommandTimeout = CommandTimeout;
if (ParameterList != null)
{
if (ParameterList.Count > 0)
{
foreach (SqlParameter parameter in ParameterList)
{
Command.Parameters.AddWithValue(
parameter.ParameterName, parameter.Value);
}
}
}
System.Data.DataTable DataTable = new System.Data.DataTable();
System.Data.SqlClient.SqlDataAdapter DataAdapter =
new System.Data.SqlClient.SqlDataAdapter();
DataAdapter.SelectCommand = Command;
DataAdapter.Fill(DataTable);
return DataTable;
}
}
最佳答案
您可以像这样堆叠语句(以尽早初始化所有一次性对象)
using (...)
using (...)
{
...
}
或者您可以对每个需要的一次性对象使用嵌套的 using 语句
using (...)
{
using (...) { ... }
using (...) { ... }
}
关于C# 'using'语句题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5774176/