加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用“使用”太多了?

发布时间:2020-12-16 00:16:28 所属栏目:百科 来源:网络整理
导读:鉴于以下代码,我认为不再需要finally块来关闭阅读器或连接(如果它仍然可用).使用这么多嵌套的“使用”语句有什么好处或缺点吗?或者我应该走最后的街区路线? Liststring platforms = new Liststring();NpgsqlDataReader reader = null;try{ using (NpgsqlCo
鉴于以下代码,我认为不再需要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();
    }
}

解决方法

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

The using statement allows the programmer to specify when objects
that use resources should release
them. The object provided to the using
statement must implement the
IDisposable interface. This interface
provides the Dispose method,which
should release the object’s resources.

A using statement can be exited either when the end of the using
statement is reached or if an
exception is thrown and control leaves
the statement block before the end of
the statement.

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

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

using (StreamWriter w1 = File.CreateText("W1"))
using (StreamWriter w2 = File.CreateText("W2"))
{
      // code here
}

另见nested using statements in C#的SO问题

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读