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

what does a using statement without variable do when disposing?(处理时不带变量的 using 语句有什么作用?)
本文介绍了处理时不带变量的 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 语句有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

ActiveDirectory error 0x8000500c when traversing properties(遍历属性时 ActiveDirectory 错误 0x8000500c)
search by samaccountname with wildcards(使用通配符按 samaccountname 搜索)
Get the list of Groups for the given UserPrincipal(获取给定 UserPrincipal 的组列表)
Can you find an Active Directory User#39;s Primary Group in C#?(你能在 C# 中找到 Active Directory 用户的主要组吗?)
Query From LDAP for User Groups(从 LDAP 查询用户组)
How can I get DOMAINUSER from an AD DirectoryEntry?(如何从 AD DirectoryEntry 获取 DOMAINUSER?)