我应该在“;使用“;陈述

本文关键字:陈述 使用 我应该 | 更新日期: 2023-09-27 17:58:07

以下两个例子中哪一个是正确的?(或者哪一个更好,我应该使用)

在MSDN中,我发现了以下内容:

private static void ReadOrderData(string connectionString)
{
   string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;"
   using (SqlConnection connection = new SqlConnection(connectionString))
   {
       SqlCommand command = new SqlCommand(queryString, connection);
       connection.Open();
       SqlDataReader reader = command.ExecuteReader();
       // Call Read before accessing data.
       while (reader.Read())
       {
           Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1]));
       }
       // Call Close when done reading.
       reader.Close();
   }
}

然而,看看其他页面,一些用户建议这样做:

private static void ReadOrderData(string connectionString)
{
   string queryString = "SELECT OrderID, CustomerID FROM dbo.Orders;";
   using (SqlConnection connection = new SqlConnection(connectionString))
   {
       using (SqlCommand command = new SqlCommand(queryString, connection))
       {
          connection.Open();
          using (SqlDataReader reader = command.ExecuteReader())
          {
              // Call Read before accessing data.
              while (reader.Read())
              {
                    Console.WriteLine(String.Format("{0}, {1}", reader[0], reader[1]));
              }
          }
       }
   }
}

因此,问题是:我应该在SqlCommandSqlDataReader中也使用using语句,还是将它们自动放置在SqlConnection using代码块的末尾。

我应该在“;使用“;陈述

第二个选项意味着reader在创建后发生异常时将被关闭,因此它是首选选项。

它被编译器有效地转换为:

SqlDataReader reader = command.ExecuteReader();
try
{
    ....
}
finally
{
  if (reader != null)
      ((IDisposable)reader).Dispose();
}

有关详细信息,请参阅MSDN。

您实际上可以一起列出using,一个la:

private static void ReadOrderData(string connectionString)
{
   string queryString =
       "SELECT OrderID, CustomerID FROM dbo.Orders;";
   using (SqlConnection connection = new SqlConnection(connectionString))
   using (SqlCommand command = new SqlCommand(queryString, connection))
   {
        connection.Open();
        using (SqlDataReader reader = command.ExecuteReader())
        {
            // Call Read before accessing data.
            while (reader.Read())
            {
               Console.WriteLine(String.Format("{0}, {1}",
               reader[0], reader[1]));
            }
        }
    }
}

使用此代码不是更简单吗?

    private static void ReadOrderData(string connectionString)
    {
        string queryString =
            "SELECT OrderID, CustomerID FROM dbo.Orders;";
        using (SqlDataReader reader = SqlHelper.ExecuteReader(connectionString, CommandType.Text, queryString))
        {
            // Call Read before accessing data.
            while (reader.Read())
            {
                Console.WriteLine(String.Format("{0}, {1}",
                reader[0], reader[1]));
            }
        }
    }

这应该在终止使用时处理读卡器以及隐式连接和命令。

或者我错过了什么?