使用"使用"太多了?

cap*_*gon 3 .net c#

鉴于以下代码,我认为不再需要finally块来关闭阅读器或连接(如果它仍然可用).使用这么多嵌套的"使用"语句有什么好处或缺点吗?或者我应该走最后的街区路线?

List<string> platforms = new List<string>();

NpgsqlDataReader reader = null;

try
{
    using (NpgsqlConnection conn = new NpgsqlConnection(GetConnectionString()))
    {
        // Making connection with Npgsql provider
        string sql = @"SELECT platforms.""name"" FROM public.""platforms""";

        using (NpgsqlCommand command = new NpgsqlCommand(sql))
        {
            command.Connection = conn;
            command.CommandType = System.Data.CommandType.Text;

            conn.Open();

            using (reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    platforms.Add((string)reader["name"].ToString());

                }
            }
        }
    }
}
catch (Exception err)
{
    HandleError(err, "GetPlatforms");

}
finally
{
    platforms = null;

    if (!reader.IsClosed)
    {
        reader.Close();
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 8

它确保在使用块完成时释放资源.每个MSDN:

using语句允许程序员指定何时使用资源的对象应该释放它们.提供给using语句的对象必须实现IDisposable接口.此接口提供Dispose方法,该方法应释放对象的资源.

当达到using语句的结尾或者抛出异常并且控制在语句结束之前离开语句块时,可以退出using语句.

我没有看到using您在代码中列出的多个语句块有任何问题.它确保释放资源,并确保程序员不会忘记.

如果您不喜欢这个标识,那么您可以重写它,如下所示:

using (StreamWriter w1 = File.CreateText("W1"))
using (StreamWriter w2 = File.CreateText("W2"))
{
      // code here
}
Run Code Online (Sandbox Code Playgroud)

另请参阅关于C#中嵌套使用语句的此SO问题