假设我有:
using(DbDataReader reader = getReader("SELECT * FROM Cmds", out DbCommand cmd))
{
}
我在其中编写了一个辅助方法 getReader
以获取 DbDataReader
和 DbCommand
。 using
语句是否在输出参数上调用 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/