C#using语句是否执行try/finally?

C#using语句是否执行try/finally?,c#,exception,using,using-statement,C#,Exception,Using,Using Statement,假设我有以下代码: private void UpdateDB(QuoteDataSet dataSet, Strint tableName) { using(SQLiteConnection conn = new SQLiteConnection(_connectionString)) { conn.Open(); using (SQLiteTransaction transaction = conn.BeginTransaction())

假设我有以下代码:

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子句


我通常用try/finally来包围我的连接,并且我总是在finally子句中关闭连接。鉴于上述代码,假设出现异常时连接将关闭是否合理?

您可以假设出现异常时连接将关闭

是的,您需要使用try/finally或using语句。你不需要两者兼而有之

A几乎与try/finally相同,只是在C#3中不能重新分配给using块中的变量

using (IDisposable d = foo())
{
     d = null; // Error:  Cannot assign to 'd' because it is a 'using variable'
}
以前您可以重新分配,但原始对象仍将被处置,而不是新分配的对象,并且您还将收到以下编译警告:

对本地“d”的赋值可能不正确,它是using或lock语句的参数。Dispose调用或解锁将在本地的原始值上发生


是的,
using
语句几乎只是
try的简写。。。最后
block

例如,此代码

using (MyDisposableType foo = new MyDisposableType())
{
    foo.DoSomething();
}
…将等同于以下内容

{
    MyDisposableType foo = new MyDisposableType();
    try
    {
        foo.DoSomething();
    }
    finally
    {
        if (foo != null)
            ((IDisposable)foo).Dispose();
    }
}
使用()。这包括关闭数据库连接,前提是
SQLiteConnection
正确处理其处理。

编译器使用(resource)语句转换
转换为以下代码:

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

(对
IDisposable
的转换是在
ResourceType
显式实现
IDisposable
的情况下进行的。

类似于没有回答您的问题。请阅读有关sql注入攻击的内容。释放不能在using语句中实例化或被重用或作为参数传递的资源的最佳方法是什么?@bjan:这取决于具体情况。释放一个不能在using语句中实例化、不能被重用或不能作为参数传递的资源的最佳方法是什么?