是什么在处置时不变量using语句呢? [英] what does a using statement without variable do when disposing?
问题描述
我带可变分配和使用始终使用。现在我有这样一类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
名为
推荐答案
从的 C#规格8.13 使用定义为
From C# Specification 8.13 using statement defined as
using-statement:
using (resource-acquisition) embedded-statement
其中的资源采集的是
resource-acquisition:
local-variable-declaration
expression
在第一种情况下,你已经使用其中获得通过局部变量声明的资源。在第二种情况下的资源是通过表达收购。所以,在第二种情况下种源将 cnctn.BeginTransaction()
调用,这是结果 DbTransaction
从 DbProviderConnection
类。 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.
更新:根据同一篇文章,你的第二个使用块将被转换为
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语句呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!