what does a using statement without variable do when disposing?

前端 未结 4 837
感动是毒
感动是毒 2020-12-17 09:01

I\'ve always used using with variable and assignment. Now i have like this a class DbProviderConnection:

public class DbProviderConnection : IDisposable
{
           


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-17 09:18

    From C# Specification 8.13 using statement defined as

    using-statement:
       using (resource-acquisition) embedded-statement
    

    Where resource-acquisition is

    resource-acquisition:
        local-variable-declaration
        expression
    

    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();
    }
    

提交回复
热议问题