Kir*_*ril 17 c# using exception using-statement
假设我有以下代码:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
C#文档声明,通过using语句,范围内的对象将被处理,并且我已经看到了几个建议我们不需要使用try/finally子句的地方.
我通常用try/finally包围我的连接,并且我总是关闭finally子句中的连接.鉴于上述代码,如果存在异常,假设连接将被关闭是否合理?
SLa*_*aks 19
你是对的; 该using语句编译为try/ finallyblock.
编译器转换using(resource) statement;为以下代码:
{
ResourceType resource = expression;
try {
statement;
}
finally {
if (resource != null) ((IDisposable)resource).Dispose();
}
}
Run Code Online (Sandbox Code Playgroud)
(转换IDisposable为以防万一ResourceType实现IDisposable.
Mar*_*ers 10
是的,您需要使用try/finally或using语句.你不需要两者.
一个using语句几乎是一样的一个try /终于只是在C#3你不能重新分配给该变量的使用块内.
using (IDisposable d = foo())
{
d = null; // Error: Cannot assign to 'd' because it is a 'using variable'
}
Run Code Online (Sandbox Code Playgroud)
以前你可以重新分配,但原始对象仍然会被处理,而不是新分配的对象,你也会得到这个编译警告:
可能是对本地'd'的赋值不正确,这是使用或锁定语句的参数.Dispose调用或解锁将发生在本地的原始值上.
是的,该using声明几乎只是一个try ... finally块的简写.
例如,这段代码......
using (MyDisposableType foo = new MyDisposableType())
{
foo.DoSomething();
}
Run Code Online (Sandbox Code Playgroud)
......等同于......
{
MyDisposableType foo = new MyDisposableType();
try
{
foo.DoSomething();
}
finally
{
if (foo != null)
((IDisposable)foo).Dispose();
}
}
Run Code Online (Sandbox Code Playgroud)