处理时不带变量的 using 语句有什么作用?
- 作者: 忆往事如风吹散哀愁
- 来源: 51数据库
- 2022-10-20
问题描述
我一直使用 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();
}
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
