处理时不带变量的 using 语句有什么作用?

时间:2022-11-03
本文介绍了处理时不带变量的 using 语句有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我一直使用 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 语句有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一条:为什么 TransactionScope 不适用于实体框架? 下一条:如何将 TransactionScope 与 MySql 和实体框架一起使用?(获取多个同时连接...目前不支持错误)

相关文章

最新文章