C#'使用'声明问题

use*_*187 7 c# dispose idisposable using-statement

如果使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Teo*_*gul 7

您可以像这样堆叠语句(尽早初始化所有一次性对象)

using (...)
using (...)
{
  ...
}
Run Code Online (Sandbox Code Playgroud)

或者您可以为所需的每个一次性对象使用嵌套的using语句

using (...)
{
   using (...) { ... }
   using (...) { ... }
}
Run Code Online (Sandbox Code Playgroud)