问题描述
我一直使用 with 变量和赋值.现在我有这样一个 DbProviderConnection 类:
I've always used using with variable and assignment. Now i have like this a class DbProviderConnection:
public class DbProviderConnection : IDisposable
{
public DbConnection Connection { get; set; }
public DbTransaction Transaction { get; set; }
public DbTransaction BeginTransaction()
{
Transaction = Connection.BeginTransaction();
return Transaction;
}
//... and so on
}
现在我想像这样使用它:
Now i was thinkin to use it like this:
using (DbProviderConnection cnctn = _planDb.CreateOpenConnection())
{
using (cnctn.BeginTransaction())
{
//...
cnctn.Transaction.Commit();
}
}
我的问题是:DbProviderConnection.Transaction.Dispose
被调用了吗?
My question is: Is the DbProviderConnection.Transaction.Dispose
called?
推荐答案
来自 C# 规范 8.13 using 定义为
From C# Specification 8.13 using statement defined as
using-statement:
using (resource-acquisition) embedded-statement
资源获取在哪里
resource-acquisition:
local-variable-declaration
expression
在第一种情况下,您使用 which 通过局部变量声明获取资源.在第二种情况下,资源是通过表达式获取的.因此,在第二种情况下,资源将是 cnctn.BeginTransaction()
调用的结果,它是来自您的 DbProviderConnection
类的 DbTransaction
.using 语句在使用后处理其资源.所以,是的,DbProviderConnection.Transaction.Dispose()
将被调用.
In first case you have using which acquires resource via local variable declaration. In second case resource is acquired via expression. So, in second case resouce will be result of cnctn.BeginTransaction()
call, which is DbTransaction
from your DbProviderConnection
class. Using statement disposes its resource after usage. So, yes, DbProviderConnection.Transaction.Dispose()
will be called.
更新:根据同一篇文章,您的第二个 using 块将被翻译为
UPDATE: According to same article, your second using block will be translated to
DbTransaction resource = cnctn.BeginTransaction();
try
{
//...
cnctn.Transaction.Commit();
}
finally
{
if (resource != null)
((IDisposable)resource).Dispose();
}
这篇关于处理时不带变量的 using 语句有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!