C# 'using'语句题

标签 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;
    }
}

最佳答案

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

using (...)
using (...)
{
  ...
}

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

using (...)
{
   using (...) { ... }
   using (...) { ... }
}

关于C# 'using'语句题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5774176/

相关文章:

c# - 接受多个 tcp 客户端的最佳方式?

c# - Xamarin 表单切换按钮

c# - 返回具有动态选择类型的 List<type>,同时转换为该类型 (C#)

linq-to-sql - 当暴露 IQueryable 时,DataContext 何时被处置?

c# - GetElementById() 找不到标签?

c# - 为什么在析构函数中调用 dispose(false)?

c# - 使用 CaSTLe Windsor 在开始新范围时我需要一个对象的新实例

c# - 了解一次性元素

c# - 处理泄漏的 IAsyncDisposable 实例的推荐方法是什么?

c# - 当从 'return' block 中调用 'using' 时会发生什么?