c# - C# 的 using 语句是否调用 Dispose on out 参数?

标签 c# ado.net

假设我有:

using(DbDataReader reader = getReader("SELECT * FROM Cmds", out DbCommand cmd))
{

}

我在其中编写了一个辅助方法 getReader 以获取 DbDataReaderDbCommandusing 语句是否在输出参数上调用 Dispose,在这种情况下为 cmd?如果没有,是否有一种简洁的方法来实现这一点,而不是像这样:

DbCommand cmd = null;
try
{
    using(DbDataReader reader = getReader("select value from cmds where typeid = 2;", out cmd))
    {

    }
}
finally
{
    cmd?.Dispose();
}

我能否返回一个包含两个一次性对象的元组,或者这只会混淆 using 语句?

我看了MSDN's documentation for C#'s using statement但它没有提到任何有关表达式中获取的out参数的内容。

最佳答案

Does the using statement call Dispose on the output parameter, cmd in this case?

不,它没有。它仅在 using 语句的括号内直接对正在创建/分配/传递的实例调用 Dispose

您可以使用多个 using 语句并像这样堆叠它们。

using(DbDataReader reader = getReader("SELECT * FROM Cmds", out DbCommand cmd))
using(cmd)
{

}

另请注意,在第一个 using 语句之后缺少左/右括号,这减少了代码缩进,并且在 cmd 之后无法引用 cmd由第二个 using 语句处理。

关于c# - C# 的 using 语句是否调用 Dispose on out 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51600631/

相关文章:

c# - Entity Framework 在 where 子句上添加了一个额外的条件

c# - 将模型导出到数据表

c# - 是否可以通过没有标题行的 ADO.NET 访问 Excel 文件?

.net - SqlDataReader如何接收数据?

asp.net - SQL Server 和 ADO.NET 中事务的区别?

c# - 字符串文字和内存表示

c# - 在 ADB2C 中忘记密码 - (AADB2C90118),如何运行特定的用户流程?

c# - 多个组件 - 性能损失?

c# - Postgres 数据库在 ADO.NET 实体数据模型中不可用

sql-server - 当没有事件连接时,SqlConnection.OpenAsync() 挂起