代码之家  ›  专栏  ›  技术社区  ›  Kiril

using语句是否执行try/finally?

  •  17
  • Kiril  · 技术社区  · 14 年前

    private void UpdateDB(QuoteDataSet dataSet, Strint tableName)
    {
        using(SQLiteConnection conn = new SQLiteConnection(_connectionString))
        {
            conn.Open();
            using (SQLiteTransaction transaction = conn.BeginTransaction())
            {
                using (SQLiteCommand cmd = new SQLiteCommand("SELECT * FROM " + tableName, conn))
                {
                    using (SQLiteDataAdapter sqliteAdapter = new SQLiteDataAdapter())
                    {
                        sqliteAdapter.Update(dataSet, tableName);
                    }
                }
                transaction.Commit();
            }
        }
    }
    

    C文档说明 using 语句范围内的对象将被释放,我看到有几个地方建议我们不需要使用try/finally子句。

    5 回复  |  直到 14 年前
        1
  •  19
  •   SLaks    14 年前

    You are correct; the using statement compiles to a try / finally block .

    编译器转换 using(resource) statement; 转换为以下代码:

    {
       ResourceType resource = expression;
       try {
          statement;
       }
       finally {
          if (resource != null) ((IDisposable)resource).Dispose();
       }
    }
    

    (演员们 IDisposable 以防万一 ResourceType 工具 可识别的 明确地。

        2
  •  10
  •   Mark Byers    14 年前

    A. using statement

    using (IDisposable d = foo())
    {
         d = null; // Error:  Cannot assign to 'd' because it is a 'using variable'
    }
    

    以前您可以重新分配,但原始对象仍将被释放,而不是新分配的对象,并且您还将得到以下编译警告:

        3
  •  6
  •   LukeH    14 年前

    是的,那个 using try ... finally 阻止。

    例如,此代码。。。

    using (MyDisposableType foo = new MyDisposableType())
    {
        foo.DoSomething();
    }
    

    {
        MyDisposableType foo = new MyDisposableType();
        try
        {
            foo.DoSomething();
        }
        finally
        {
            if (foo != null)
                ((IDisposable)foo).Dispose();
        }
    }
    
        4
  •  1
  •   MadBoy    14 年前

    如果出现异常,可以假设连接将关闭。

        5
  •  1
  •   3Dave    14 年前

    SQLiteConnection 正确处理其处置。